直接放上代码,使用@RestControllerAdvice进行controller层的处理
/**
* @author Relic
*/
@Slf4j
@RestControllerAdvice
public class BusinessExceptionHandler {
/**
* 处理自定义异常
*/
@ExceptionHandler(BusinessException.class)
public Result handleBusinessException(BusinessException e) {
return new Result(false, e.getMsg(), 500);
}
@ExceptionHandler(NoHandlerFoundException.class)
public Result handlerNoFoundException(Exception e) {
log.error(e.toString(), e);
return new Result(false, "路径不存在,请检查路径是否正确", 404);
}
@ExceptionHandler(DuplicateKeyException.class)
public Result handleDuplicateKeyException(DuplicateKeyException e) {
log.error(e.toString(), e);
return new Result(false, "数据库中已存在该记录", 500);
}
@ExceptionHandler(Exception.class)
public Result handleException(Exception e) {
return ResultUtils.exceptionResult(e);
}
}
RestControllerAdvice无法处理404,此处解决404
/**
* @author Relic
* @desc 404错误处理
* @date 2019-05-15 14:34
*/
@RestController
public class NotFoundController implements ErrorController {
@Override
public String getErrorPath() {
return "/error";
}
@RequestMapping("/error")
public Result error() {
return new Result(false, "路径不存在,请检查路径是否正确", 404);
}
}
自定义异常类
/**
* @author Relic
* @desc 业务异常
* @date 2019-03-08 17:30
*/
@Getter
@Setter
@ToString
public class BusinessException extends RuntimeException {
private int code = 500;
private String msg;
public BusinessException(String msg) {
super(msg);
this.msg = msg;
}
}