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, "找不到頁面!!!");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章