Spring Boot项目中Restful API错误异常处理

2016-12-04  本文已影响1921人  SHUTUP

前言

在设计Restful 风格API时,如何进行错误响应,也是一个重要的环节。我在实践中发现,如果可以统一封装错误响应,那么会给调用者带来很大的便利。下面就来说说使用Spring Boot框架时,如何进行统一的错误响应。

在Spring Boot项目中有3种级别的异常处理:

为了演示如何使用上面的方式进行错误处理,我们假定拥有三个类

我们会创建以下几种方法,来触发不同的异常

接着我们来看如何使用上面提到的处理流程来处理不同的异常。

我们创建一个类,用 **@ControllerAdvice **和 @RestController修饰。 这表明本类可以返回一个Rest的响应。
@ControllerAdvice 表明本类会进行应用全局的异常处理。
@RestController 表明本类是一个Controller
使用 @ExceptionHandler 注解 定义需要捕获的异常类. (基类异常会捕获派生类异常)
用可以通过使用 @ResponseStatus 注解来修改响应的返回状态。

** HomeController.class **
<pre>
package com.ekiras.controller;

import com.ekiras.exception.BaseException;
import com.ekiras.exception.CustomException1;
import com.ekiras.exception.CustomException2;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**

GlobalExceptionHandler.class
<pre>
package com.ekiras.handler.exception;

import com.ekiras.exception.BaseException;
import com.ekiras.exception.CustomException1;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

/**

结论:

参考

http://www.ekiras.com/2016/02/how-to-do-exception-handling-in-springboot-rest-application.html

上一篇 下一篇

猜你喜欢

热点阅读