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版本新方式。

?

猜你喜欢

转载自cargoj.iteye.com/blog/1840715