美文网首页
【Java】Spring Boot(八)全局异常处理

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

作者: 印比八方来 | 来源:发表于2019-04-19 23:13 被阅读0次

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(八)全局异常处理

      本文链接:https://www.haomeiwen.com/subject/zayhgqtx.html