原文讲的是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版本新方式。