本文介绍SpringMVC中的异常处理,@Controller注解的方法可能由于各种各样的原因抛出异常,如果没有写try...catch()...语句,异常的堆栈信息将直接抛给浏览器,这样对用户来说很不友好,并且异常的堆栈信息可能含有一些敏感信息(如数据库的表字段,sql语句等等...)是不能暴露出去的。因此在程序中最好捕捉到所有的异常并处理后将友好的界面或者信息返回给客户端,SpringMVC提供了一个Handler,该handler指定一种异常,并返回一个view,举个例子,增加一个Controller,叫ExceptionController:
?
package org.springframework.samples.mvc.exceptions; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class ExceptionController { @ExceptionHandler public @ResponseBody String handle(IllegalStateException e) { return "IllegalStateException handled!"; } @RequestMapping("/exception") public @ResponseBody String exception() { throw new IllegalStateException("Sorry!"); } }
?
@ExceptionHandler注解的方法接收一个异常类型的参数,返回值类型和@RequestMapping一样(String,void,ModelAndView...),
访问http://localhost:8080/web/exception,浏览器显示"IllegalStateException handled!"