springmvc ajax全局异常处理

我转载的这里:http://www.baeldung.com/2013/01/31/exception-handling-for-rest-with-spring-3-2/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+Baeldung+%28baeldung%29

原文讲的是rest风格中的异常处理,不过通用性也不错。

 

 

2. Via Controller level @ExceptionHandler

Defining a Controller level method annotated with @ExceptionHandler is very easy:

 

public class FooController{
    ...
    @ExceptionHandler({ CustomException1.class, CustomException2.class })
    public void handleException() {
        //
    }
}

作为base controller继承,有一个限制就是你的controller可能必须继承其他类。

 

3. Via HandlerExceptionResolver

分别介绍了

3.1 spring3.1版本的ExceptionHandlerExceptionResolver,实际@ExceptionHandler就是靠它实现的。

3.2 spring3.0版本的DefaultHandlerExceptionResolver,ResponseStatusExceptionResolver。限制在于无法控制response body。

3.3 

SimpleMappingExceptionResolver and AnnotationMethodHandlerExceptionResolver

前者是异常与VIEW的映射,跟AJAX异常没什么关系,后者在3.2中已经被ExceptionHandlerExceptionResolver取代。

3.4 

Custom HandlerExceptionResolver

自己实现异常处理,我只是做测试,实际要根据需要来写。直接继承了SimpleMappingExceptionResolver在其中判断如果header是application/json就只是简单设置status为500,前台extjs ajax 在头中用application/json覆盖默认设置,后台出现异常会进入failure。

4. Via new @ControllerAdvice (Spring 3.2 Only)

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler(value = { IllegalArgumentException.class, IllegalStateException.class })
    protected ResponseEntity<Object> handleConflict(RuntimeException ex, WebRequest request) {
        String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse,
          new HttpHeaders(), HttpStatus.CONFLICT, request);
    }
}

 推荐的3.2版本新方式。

?

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值