MENU

springboot配置全局异常处理返回结果

March 15, 2021 • 开发

首先得需配置好全局统一返回,出现异常之后返回失败信息即可

springboot 定义统一返回类

①在common目录下,新建一个BaseExceptionHandler.java

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author xupt
 */
@RestControllerAdvice
@Slf4j
public class BaseExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResultVO exception(Exception e){
        log.error(e.getMessage());
        return new ResultVO(ResCode.ERROR,e.getMessage());
    }
}

②测试实例

@GetMapping("test")
public ResultVO test(int num){
      return new ResultVO(ResCode.SUCCESS,(1/num));
}

请求http://localhost:8080/test?num=0

返回结果:

{
  "code": 0,
  "msg": "error",
  "data": "/ by zero"
}
转载请注明出处,并添加原文地址

Archives QR Code Tip
QR Code for this page
Tipping QR Code