Spring Booot Web @RestControllerAdvice 异常拦截何统一处理

1.pom

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

2.自定义异常信息

@Data
@NoArgsConstructor
public class ExceptionInfo<T> {

    public static final Integer OK = 0;
    public static final Integer ERROR = 100;
    private Integer httpStatus;
    private Integer code;
    private String message;
    private String url;
    private T data;

    public ExceptionInfo(Integer httpStatus, Integer code, String message) {
        this.httpStatus = httpStatus;
        this.code = code;
        this.message = message;
    }
}

3.自定义全局异常

@Data
public class GlobalException extends RuntimeException {

    private Integer code = 100;
    private String message = "exception";

    public GlobalException(Integer code, String message) {
        this.code = code;
        this.message = message;
    }
}

4.统一异常处理

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {Exception.class})
    public ExceptionInfo<String> jsonErrorHandler(HttpServletRequest request, HttpServletResponse response,
                                                  Exception e) throws Exception {
        ExceptionInfo<String> r = new ExceptionInfo<>();
        if (e instanceof MyBatisSystemException) {
            r.setCode(HttpStatus.EXPECTATION_FAILED.value());
            response.setStatus(HttpStatus.EXPECTATION_FAILED.value());
            r.setMessage("数据库操作异常");
        } else if (e instanceof GlobalException) {
            r.setCode(((GlobalException) e).getCode());
            r.setMessage(e.getMessage());
            response.setStatus(((GlobalException) e).getCode());
        }
        r.setData(e.getMessage());
        r.setUrl(request.getRequestURL().toString());
        log.error(e.getMessage());
        return r;
    }
}

5.测试

@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/error")
    public String test() {
        throw new GlobalException(404, "找不到页面!!!");
    }
}
发布了29 篇原创文章 · 获赞 0 · 访问量 365

猜你喜欢

转载自blog.csdn.net/qq_43399077/article/details/104068454