首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Ajax >

springmvc ajax全局错误处理

2013-04-07 
springmvc ajax全局异常处理我转载的这里:http://www.baeldung.com/2013/01/31/exception-handling-for-re

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

?

?

热点排行