springboot统一处理异常
增加业务异常处理类:
package com.example.demo.config; import lombok.Data; @Data public class BizException extends RuntimeException{ protected Integer errorCode; protected String errorMsg; public BizException(){ } public BizException(Integer errorCode, String errorMsg) { this.errorCode = errorCode; this.errorMsg = errorMsg; } }
设置异常handler:
package com.example.demo.config;
import lombok.Data;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@Data
class ErrorObj<T>{
//是否成功
private Boolean success;
//状态码
private Integer code;
//提示信息
private String msg;
//数据
private T data;
}
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value =Exception.class)
@ResponseBody
public ErrorObj exceptionHandler(Exception e){
System.out.println("发生了一个运行时异常"+e);
ErrorObj errObj = new ErrorObj();
errObj.setSuccess(false);
errObj.setCode(1);
errObj.setMsg(e.getMessage());
errObj.setData("");
return errObj;
}
@ExceptionHandler(value =BizException.class)
@ResponseBody
public ErrorObj bizexceptionHandler(BizException e){
System.out.println("发生了一个业务异常"+e);
ErrorObj errObj = new ErrorObj();
errObj.setSuccess(false);
errObj.setCode(e.getErrorCode());
errObj.setMsg(e.getErrorMsg());
errObj.setData("");
return errObj;
}
}
测试:
@RequestMapping("/hello")
public void hello() throws BizException {
throw new BizException(1, "我抛出了一个错误");
}
@RequestMapping("/zeroException")
public Integer zeroException(){
return 100/0;
}
执行结果:
{"success":false,"code":1,"msg":"/ by zero","data":""}
{"success":false,"code":1,"msg":"我抛出了一个错误","data":""}
命令行输出:

本文来自博客园,作者:河北大学-徐小波,转载请注明原文链接:https://www.cnblogs.com/xuxiaobo/p/17062755.html

浙公网安备 33010602011771号