SPRING MVC3.2案例讲解--异常处理

SPRING MVC 异常处理 可以全局进行定义,也可以单独在SPRING controller中定义;同时SPRING MVC将异常处理的代码和业务逻辑进行分离,将异常的处理放到一个单独的带有@ExceptionHandler方法中;

 

@Controller
public class ExceptionController {

      
	@RequestMapping("/exception")
	public @ResponseBody String exception() {
		throw new IllegalStateException("Sorry!");
	}

       // 处理异常的代码,这样就实现了业务逻辑和异常处理的分离
	@ExceptionHandler
	public @ResponseBody String handle(IllegalStateException e) {
		return "IllegalStateException handled!";
	}

	@RequestMapping("/global-exception")
	public @ResponseBody String businessException() throws BusinessException {
		throw new BusinessException();
	}

}

 

SPRING 处理异常的流程:

1.WEB启动时ExceptionHandlerExceptionResolver 扫描到通用的异常处理方法:

DEBUG ExceptionHandlerExceptionResolver Looking for exception mappings: WebApplicationContext for namespace 'appServlet-servlet': startup date [Sat Jun 08 08:40:41 GMT 2013]; parent: Root WebApplicationContext

 

INFO  ExceptionHandlerExceptionResolver Detected @ExceptionHandler methods in globalExceptionHandler

 

2.当请求出现异常时,首先看当前类中是否含有@ExceptionHandler的处理方法

DEBUG ExceptionHandlerExceptionResolver Resolving exception from handler [public java.lang.String org.springframework.samples.mvc.exceptions.ExceptionController.exception()]: java.lang.IllegalStateException: Sorry!

DEBUG ExceptionHandlerExceptionResolver Invoking @ExceptionHandler method: public java.lang.String org.springframework.samples.mvc.exceptions.ExceptionController.handle(java.lang.IllegalStateException)

DEBUG RequestResponseBodyMethodProcessor Written [IllegalStateException handled!] as "text/plain;charset=ISO-8859-1" using [org.springframework.http.converter.StringHttpMessageConverter@163e9a1]

 

3.然后看有没有含有@ExceptionHandler method 的类,另外该类必须@ControllerAdvice

DEBUG ExceptionHandlerExceptionResolver Resolving exception from handler [public java.lang.String org.springframework.samples.mvc.exceptions.ExceptionController.businessException() throws org.springframework.samples.mvc.exceptions.BusinessException]: org.springframework.samples.mvc.exceptions.BusinessException

DEBUG ExceptionHandlerExceptionResolver Invoking @ExceptionHandler method: public java.lang.String org.springframework.samples.mvc.exceptions.GlobalExceptionHandler.handleBusinessException(org.springframework.samples.mvc.exceptions.BusinessException)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值