Spring MVC中的异常处理

在一个良好的Rest架构的应用中,所有的异常都应该有对应的Http Status Code来表示具体的异常类型,这样可以客户端可以基于对应的Status Code做出最有利于自己的处理。

在Spring MVC中,异常处理机制有3个选项:
  • 基于Exception的,即只处理某个异常
  • 基于Controller的,即处理某个Controller中抛出的异常。
  • 基于Application的,即处理该Application抛出的所有异常

在我之前的文章( http://ningandjiao.iteye.com/blog/1982635)中,搭建了一个基于Spring4.0的Restful服务,下面就来为这个服务添加Error Handling机制,

基于Exception的异常处理
通常情况下,在应用中抛出的未被捕获的异常,最后会以500(HttpStatus.INTERNAL_SERVER_ERROR)返回客户端,但是,有时服务器的异常是由于客户端发送的请求不合规范导致,这时,我们就需要应该400(BAD_REQUEST)的status code。在Spring MVC中,做到这点非常容易,只需要在对应的Exception上加上@ResponseStatus注解即可。栗子:

测试代码:
    @Test
    public void shouldGetStatus404WhenRquestIdBiggerThan10() throws Exception {
        mockMvc.perform(get("/requests/11")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .param("userId", "xianlinbox")
        )
                .andExpect(status().isBadRequest());
    }

实现代码:
@RequestMapping(value = "/requests/{requestId}", method = RequestMethod.GET)
    public Request get(@PathVariable int requestId, @RequestParam(value = "userId") String userId) {
        if (requestId > 10) {
            throw new InvalidRequestIdException("Request id must less than 10");
        }
        return new Request(userId, requestId, "GET");
    }
    
    
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Request id must less than 10")
public class InvalidRequestIdException extends RuntimeException {
    public InvalidRequestIdException(String message) {
        super(message);
    }
}

这个方式有很大的局限性:

1. 只能处理自己写的Exception
2. 不能定制Response的消息体。

基于Controller的异常处理
在每个Controller中,可以定义处理各种异常的方法,在该方法添加@ExceptionHandler定义该方法处理的Exception(所有的Exception都支持),添加@ResponseStatus定义该Exception应该返回的Http Status Code,方法的返回值可以是定制化的异常信息, 这就解决了上面Exception方式的局限性。 栗子:
测试代码:

    @Test
    public void shouldGetStatus404WhenRquestIdBiggerThan10() throws Exception {
        mockMvc.perform(get("/requests/11")
                .param("userId", "xianlinbox")
        )
                .andExpect(status().isBadRequest())
                .andExpect(content().string("Request id must less than 10"));

    }

    @Test
    public void shouldGetStatus500WhenUnexpectedErrorHappen() throws Exception {
        mockMvc.perform(get("/requests/100")
                .param("userId", "xianlinbox")
        )
                .andExpect(status().isInternalServerError())
                .andExpect(content().string("Unexpected Server Error"));
    }


实现代码:
    @ExceptionHandler(InvalidRequestIdException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public String handleInvalidRequestError(InvalidRequestIdException ex) {
        return ex.getMessage();
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public String handleUnexpectedServerError(RuntimeException ex) {
        return ex.getMessage();
    }


这种处理方式其它都好,就是有个最大的弊端,只能处理一个Controller的异常,对于又多个Controller的情况就会搞出很多的重复代码。

基于Application的异常处理
我个人觉得一个好的异常处理机制应该是这样的,有一个集中的处理点负责所有的异常处理,在真正的业务逻辑的处理过程中,我只会关心正常的业务流程,一旦遇到异常,我只管抛出对应的异常和相关的信息就行了。幸运的是,Spring MVC就提供了这样的机制,开发者可以自己定义一个ExceptionHandler类处理所有的异常,在这个类上加上@ControllerAdvice注解,这个类就以AOP的形式注册到SpringMVC的处理链条中了,在应用任何地方抛出Exception,最后都会调用到这个handler中的方法上,在Handler类中,可以和上面一样使用@ExceptionHandler注解来区别对待不同的Exception。栗子:

测试代码:
同上:但是需要注意一点,使用@ControllerAdvice是以AOP的形式做了一个切面处理异常,因此,你必须模拟整个Web处理过程该注解才能起效。因此在Integration测试类中,你需要加上@WebAppConfiguration注解,同时使用WebApplicationContext构建MockMvc,使用基于Controller的standaloneSetup是不能达到想要的效果的。
@WebAppConfiguration
public class ApiControllerIntegrationTest {
    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }
...

实现代码:
@ControllerAdvice
public class ApiExceptionHandler {

    @ExceptionHandler(InvalidRequestIdException.class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    @ResponseBody
    public String handleInvalidRequestError(InvalidRequestIdException ex) {
        return ex.getMessage();
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public String handleUnexpectedServerError(RuntimeException ex) {
        return ex.getMessage();
    }
}

猜你喜欢

转载自ningandjiao.iteye.com/blog/1995270