我们想要将项目中的异常统一在controller层中抛出,这样就减少了对每一次异常的处理。在这里介绍一些springboot统一异常的处理方式。
自定义基础接口类
首先定义一个基础的接口类
public interface BaseErrorInfoInterface {
//错误码
String getResultCode();
//错误描述
String getResultMsg();
}
自定义枚举类
我们来继承接口类进行拓展
public enum CommonEnum implements BaseErrorInfoInterface{
SUCCESS("200","成功"),
BODY_NOT_MATCH("400","请求数据格式不符"),
SIGNATURE_NOT_MATCH("401","请求的数字签名不匹配"),
NOT_FOUND("404","未找到该资源"),
INTERNAL_SERVER_ERROR("500","服务器内部错误"),
SERVER_BUSY("503","服务器正忙,请稍后再试!")
;
//错误码
private String resultCode;
//错误描述
private String resultMsg;
@Override
public String getResultCode() {
return resultCode;
}
@Override
public String getResultMsg() {
return resultMsg;
}
CommonEnum(String resultCode,String resultMsg){
this.resultCode=resultCode;
this.resultMsg=resultMsg;
}
}
自定义异常类
这个类,其实可有可无,但是为了理解清楚,自定义的异常也是可以被捕获的。
package com.springboot.springboot.test;
public class BizException extends RuntimeException{
private static final long serivalVersionUID=1L;
//错误码
protected String errorCode;
//错误信息
protected String errorMsg;
public BizException(){
super();
}
public BizException(BaseErrorInfoInterface errorInfoInterface){
super(errorInfoInterface.getResultCode());
this.errorCode=errorInfoInterface.getResultCode();
this.errorMsg=errorInfoInterface.getResultMsg();
}
public BizException(BaseErrorInfoInterface errorInfoInterface,Throwable cause){
super(errorInfoInterface.getResultCode(),cause);
this.errorCode=errorInfoInterface.getResultCode();
this.errorMsg=errorInfoInterface.getResultMsg();
}
public BizException(String errorMsg){
super(errorMsg);
this.errorMsg=errorMsg;
}
public BizException(String errorCode ,String errorMsg){
super(errorCode);
this.errorMsg=errorMsg;
this.errorCode=errorCode;
}
public BizException(String errorCode, String errorMsg, Throwable cause) {
super(errorCode, cause);
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
public String getMessage() {
return errorMsg;
}
@Override
public Throwable fillInStackTrace() {
return this;
}
}
自定义数据格式
这里是比较重要的,在很多场合都是需要的。建议多看看。
package com.springboot.springboot.test;
import org.json.JSONObject;
public class ResultBody {
//响应代码
private String code;
//响应消息
private String message;
//响应结果
private Object result;
public ResultBody(){
}
public ResultBody(BaseErrorInfoInterface errorInfoInterface){
this.code=errorInfoInterface.getResultCode();
this.message=errorInfoInterface.getResultMsg();
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
public static ResultBody success(){
return success(null);
}
public static ResultBody success(Object data){
ResultBody rb=new ResultBody();
rb.setCode(CommonEnum.SUCCESS.getResultCode());
rb.setMessage(CommonEnum.SUCCESS.getResultMsg());
rb.setResult(data);
return rb;
}
public static ResultBody error(BaseErrorInfoInterface errorInfo) {
ResultBody rb = new ResultBody();
rb.setCode(errorInfo.getResultCode());
rb.setMessage(errorInfo.getResultMsg());
rb.setResult(null);
return rb;
}
/**
* 失败
*/
public static ResultBody error(String code, String message) {
ResultBody rb = new ResultBody();
rb.setCode(code);
rb.setMessage(message);
rb.setResult(null);
return rb;
}
/**
* 失败
*/
public static ResultBody error( String message) {
ResultBody rb = new ResultBody();
rb.setCode("-1");
rb.setMessage(message);
rb.setResult(null);
return rb;
}
// @Override
// public String toString() {
// return JSONObject.toJSONString(this);
// }
}
自定义全局异常处理类
这是最重要的一步,也是异常处理的核心。
package com.springboot.springboot.test;
import com.sun.istack.internal.logging.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@ControllerAdvice
public class GlobalExceptionHandler {
// private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理自定义的业务异常
* @param req
* @param e
* @return
*/
@ExceptionHandler(value = BizException.class)
@ResponseBody
public ResultBody bizExceptionHandler(HttpServletRequest req, BizException e){
// logger.error("发生业务异常!原因是:{}",e.getErrorMsg());
return ResultBody.error(e.getErrorCode(),e.getErrorMsg());
}
/**
* 处理空指针的异常
* @param req
* @param e
* @return
*/
@ExceptionHandler(value =NullPointerException.class)
@ResponseBody
public ResultBody exceptionHandler(HttpServletRequest req, NullPointerException e){
// logger.error("发生空指针异常!原因是:",e);
return ResultBody.error(CommonEnum.NOT_FOUND);
}
/**
* 处理其他异常
* @param req
* @param e
* @return
*/
@ExceptionHandler(value =Exception.class)
@ResponseBody
public ResultBody exceptionHandler(HttpServletRequest req, Exception e){
// logger.error("未知异常!原因是:",e);
return ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
}
}
在类的上面有一个注解@ControllerAdvice这个注解是增强注解,可以去捕获到异常,@ExceptionHandler这个注解的作用是需要捕获异常的类型
开始测试
实体类
package com.springboot.springboot.test;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
/** 编号 */
private int id;
/** 姓名 */
private String name;
/** 年龄 */
private int age;
public User(){
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Controller控制层
package com.springboot.springboot.test;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
@CrossOrigin
public class UserRestController {
@RequestMapping("user")
public boolean insert(@RequestBody User user){
System.out.println("开始新增");
if (user.getName()==null){
throw new BizException("-1","用户姓名不能为空");
}
return true;
}
@RequestMapping("update")
public boolean update(@RequestBody User user) {
System.out.println("开始更新...");
//这里故意造成一个空指针的异常,并且不进行处理
String str=null;
str.equals("111");
return true;
}
@RequestMapping("delete")
public boolean delete(@RequestBody User user) {
System.out.println("开始删除...");
//这里故意造成一个异常,并且不进行处理
Integer.parseInt("abc123");
return true;
}
@RequestMapping("find")
public List<User> findByUser(User user) {
System.out.println("开始查询...");
List<User> userList =new ArrayList<>();
User user2=new User();
// user2.setId(1L);
user2.setName("xuwujing");
user2.setAge(18);
userList.add(user2);
return userList;
}
}
运行代码开始测试,你会看到你想要的情况(本人亲测有效)