@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("数据库操作异常");}elseif(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, "找不到页面!!!");}}