@RestControllerAdvice
@Slf4j
public class FinanceExceptionAdvice {
@ResponseBody
@ExceptionHandler(Exception.class)
public Result exceptionHandler(Exception e) {
log.error("执行异常", e);
if (e instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
return Result.getBusinessException(exception.getMessage(), ResponseStatus.BUSINESS_ERROR_STATUS.getCode());
} else if (e instanceof OrderException) {
OrderException exception = (OrderException) e;
return Result.getBusinessException(exception.getMessage(), ResponseStatus.BUSINESS_ERROR_STATUS.getCode());
} else {
return Result.getBusinessException("后台异常,请联系管理员!", ResponseStatus.BUSINESS_ERROR_STATUS.getCode());
}
}
}
其中OrderException是根据业务自定义的异常
import java.io.Serializable;
public class OrderException extends RuntimeException implements Serializable {
private static final long serialVersionUID = 6037840863824232187L;
private String code;
public OrderException() {
}
public OrderException(String message, Throwable cause) {
super(message, cause);
}
public OrderException(String message) {
super(message);
}
public OrderException(Throwable cause) {
super(cause);
}
public OrderException(String message, String code) {
super(message);
this.code = code;
}
public OrderException(String message, String code, Throwable cause) {
super(message, cause);
this.code = code;
}
public String getCode() {
return this.code;
}
}