默认情况下,Spring会将自身的一些异常自动转换为合适的状态码,映射关系如下
Spring异常 | HTTP状态码 |
BindException | 400 - Bad Request |
ConversionNotSupportedException | 500 - Internal Server Error |
HttpMediaTypeNotAcceptableException | 406 - Not Acceptable |
HttpMediaTypeNotSupportedException | 415 - Unsupported Media Type |
HttpMessageNotReadableException | 400 - Bad Request |
HttpMessageNotWritableException | 500 - Internal Server Error |
HttpRequestMethodNotSupportedException | 405 - Method Not Allowed |
MethodArgumentNotValidException | 400 - Bad Request |
MissingServletRequestParameterException | 400 - Bad Request |
MissingServletRequestPartException | 400 - Bad Request |
NoSuchRequestHandlingMethodException | 404 - Not Found |
TypeMismatchException | 400 - Bad Request |
类似这种效果
我们可以自定义异常映射为特定的状态码
@ResponseStatus(value = HttpStatus.NOT_FOUND,reason = "data not exist")
public class NotExistException extends RuntimeException {
}
@RestController
public class IndexController {
@RequestMapping("/test")
@ResponseBody
public String test(String param) {
System.out.println("param:" + param);
if (param == null) {
throw new NotExistException();
}
return param;
}
}
效果如图
处理当前controller中的异常
@RestController
public class IndexController {
@RequestMapping("/test")
@ResponseBody
public String test(String param) {
System.out.println("param:" + param);
if (param == null) {
throw new NotExistException();
}
return param;
}
@ExceptionHandler(NotExistException.class)
public String handlerNotExistException() {
return "123";
}
}
再次调用效果如下,这里异常已经被ExceptionHandler捕获了
如果需要全局捕获需要引入新的解决方案:控制器通知(controller advice)。控制器通知是任意带有@ControllerAdvice注解的类
@RestControllerAdvice
public class ExceptionConfig {
@ExceptionHandler(NotExistException.class)
public String handlerNotExistException() {
return "123";
}
}
ExceptionConfig中的注解需要与Controller中的注解一致(@RestControllerAdvice对应controller中的@RestController、@ControllerAdvice对应controller中的@Controller)否则会不生效