@RestControllerAdvice
自定义一个类,添加如上注解,此注解相当于同时注解了
@ControllerAdvice @ResponseBody
添加此注解,本类就支持异常捕获了,我们定义一个方法,在方法上添加注解
@ExceptionHandler(Exception.class)
那么所有异常都会被这个方法捕获,我们可以在方法内定义统一的返回数据了。
我下面写了一个例子
@RestControllerAdvice
public class ControllerException {
private ErrorResponseBean createErrorBean(int httpStatus, int code, String message, HttpServletRequest request) {
ErrorResponseBean bean = new ErrorResponseBean();
bean.setCode(code);
bean.setHttpStatus(httpStatus);
bean.setException(message);
if (null != request) {
bean.setPath(request.getRequestURI());
}
bean.setTimestamp(new Date());
return bean;
}
@ResponseStatus(value = HttpStatus.UNAUTHORIZED) //返回数据时,http返回码
@ExceptionHandler(UnAuthorizedException.class)
public ErrorResponseBean handleUnAuthorizedException(UnAuthorizedException exception, HttpServletRequest request) {
return createErrorBean(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.value(), exception.getMessage(), request);
}
/**
* 处理服务器端数据库处理错误
*/
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler({SQLException.class, DataAccessException.class, DataAccessResourceFailureException.class,
DataException.class, DataIntegrityViolationException.class})
public ErrorResponseBean handleSQLException(HttpServletRequest request, Exception exception) {
String message = exception.getLocalizedMessage();
if (exception.getCause() instanceof ConstraintViolationException) {
ConstraintViolationException e = (ConstraintViolationException) exception.getCause();
message = e.getSQLException().getLocalizedMessage();
}
return createErrorBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.value(), message, request);
}
/**
* 处理服务器端其他错误异常
*/
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(Exception.class)
public ErrorResponseBean handleOtherException(HttpServletRequest request, Exception exception) {
return createErrorBean(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.value(), exception.getMessage(), request);
}
}
这个例子中,处理了登录异常(这个Exception是自定义的),数据库异常(包含很多异常),以及其他异常。