public abstract class ResponseEntityExceptionHandler {
//不支持的HTTP请求方法异常信息处理方法
protected ResponseEntity
我们选择性的覆盖几个常用的异常处理方法,并添加我们自定义异常处理方法:
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
protected ResponseEntity handleUserNotFound(UserNotFoundException ex){
RestApiError apiError = new RestApiError(HttpStatus.NOT_FOUND);
apiError.setMessage(ex.getMessage());
return buildResponseEntity(apiError);
}
@Override
protected ResponseEntity handleMissingServletRequestParameter(
MissingServletRequestParameterException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
String error = ex.getParameterName() + " parameter is missing";
return buildResponseEntity(new RestApiError(BAD_REQUEST, error, ex));
}
@Override
protected ResponseEntity handleHttpMediaTypeNotSupported(
HttpMediaTypeNotSupportedException ex,
HttpHeaders headers,
HttpStatus status,
WebRequest request) {
StringBuilder builder = new StringBuilder();
builder.append(ex.getContentType());
builder.append(" media type is not supported. Supported media types are ");
ex.getSupportedMediaTypes().forEach(t -> builder.append(t).append(", "));
return buildResponseEntity(new RestApiError(HttpStatus.UNSUPPORTED_MEDIA_TYPE, builder.substring(0, builder.length() - 2), ex));
}
...
}
UserNotFoundException类为我们自定义异常信息类,在执行GET /users/{userIds}或 GET /users请求时,如果数据库中不存在该ID的记录信息,将抛出UserNotFoundException异常信息,且将响应状态码设置为NOT_FOUND。UserNotFoundException源码如下:
public class UserNotFoundException extends Exception {
public UserNotFoundException(Class clz,String...searchParams){
super(UserNotFoundException.generateMessage(clz.getSimpleName(),toMap(String.class,String.class,searchParams)));
}
private static String generateMessage(String entity, Map searchParams){
return StringUtils.capitalize(entity)+
" was not found for parameters "+
searchParams;
}
private static Map toMap(Class key,Class value,Object...entries){
if(entries.length % 2 == 1){
throw new IllegalArgumentException("Invalid entries");
}
return IntStream.range(0,entries.length/2).map(i->i*2)
.collect(HashMap::new,
(m,i)->m.put(key.cast(entries[i]),value.cast(entries[i+1])),Map::putAll);
}
}