---
title: "springmvc ajax全局异常处理"
author: "cargoj"
date: "2013-04-02T13:53:42Z"
tags: []
categories: ["企业架构"]
slug: "springmvc-ajax"
draft: false
lastmod: "2013-04-02T13:53:42Z"
id: 1840715
url: "https://cargoj.iteye.com/blog/1840715"
---

我转载的这里：[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](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%20Baeldung%20%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版本的D***efaultHandlerExceptionResolver，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版本新方式。

[?](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%20Baeldung%20%28baeldung%29)