1.定义一个CommonException类
2.定义一个全局异常捕获类GlobalExceptionHandler,添加@RestControllerAdvice注解
代码:
@Getter
public class CommonException extends RuntimeException {
private final String code;
private final String msg;
public CommonException() {
this.code = "400";
this.msg = "操作失败";
}
public CommonException(String code, String msg) {
this.code = code;
this.msg = msg;
}
}
@RestControllerAdvice
@Component
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(CommonException.class)
public ObjectResult commonExceptionHandler(CommonException e) {
log.error("Catch CommonException:", e);
return new ObjectResult(e.getCode(), e.getMsg());
}
@ExceptionHandler(RuntimeException.class)
public ObjectResult runtimeExceptionHandler(RuntimeException e) {
log.error("Catch RuntimeException:", e);
return ObjectResult.error("操作失败");
}
}