【Java】Spring Boot(八)全局异常处理

1.定义一个异常处理类

import com.sosocode.oneme.vo.reponse.ResponseVO;
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 {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseVO defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {

//        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
//            r.setCode(404);
//        } else {
//            r.setCode(500);
//        }
        e.printStackTrace();
        return ResponseVO.UsuallyBadService("业务异常");
    }
}

2.配置文件中加上如下配置,我用的是yml

spring:
  # 全局异常捕捉
  mvc:
    throw-exception-if-no-handler-found: true
  resources:
    add-mappings: false

你可能感兴趣的:(【Java】Spring Boot(八)全局异常处理)