一、将异常映射为HTTP状态码
1.1 spring异常与HTTP状态码
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 |
1.2 通过@ResponseStatus注解将异常映射为HTTP状态码
1)定义异常
通过@ResponseStatus注解可以把异常映射为对应的HTTP状态码。
HttpStatus类提供了HTTP状态码的常量。
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Resource Not Found")
public class MySpringException extends RuntimeException {
}
2)使用异常
下面的代码中,当id的值大于10的时候浏览器就会抛出404错误。
@RequestMapping(value = "test/{id}",method = RequestMethod.POST, produces = "application/json")
@ResponseBody
public String exception(@PathVariable("id") int id){
if (id > 10) {
throw new MySpringException();
}
return "SUCCESS";
}
3)运行结果
启动程序访问
http://localhost:8000/test/11
时则会出现如下效果:
当请求http://localhost:8000/test/10
出现如下效果:
1.3 编写异常处理的方法
1)在控制器中定义处理异常的方法
在此控制器内所有抛出这个错误的方法都会执行此方法。
@ExceptionHandler(ArithmeticException.class)
public String error() {
System.out.println("error!");
return "error";
}
2)定义测试方法
当测方法抛出ArithmeticException异常时(i等于0时),就是执行error()方法。
@RequestMapping("/error")
public String testError(@RequestParam("i") int i){
System.out.println("result: "+(10/i));
return "home";
}
1.4 为控制器添加通知
控制器通知(controller advice)是任意带有@ControllerAdvice注解的类,这个类会包含一个或多个如下类型的方法:
- @ExceptionHandler注解标注的方法;
- @InitBinder注解标注的方法;
- @ModelAttribute注解标注的方法。
在带有@ControllerAdvice注解的类中,以上所述的这些方法会运用到整个应用程序所有控制器中带有@RequestMapping注解的方法上。
@ControllerAdvice注解本身已经使用了@Component,因此@ControllerAdvice注解所标注的类将会自动被组件扫描获取
到,就像带有@Component注解的类一样。
1)示列:定义一个全局的错误处理方法
当所有带有@RequestMapping主机的方法抛出ArithmeticException异常时都会出现error方法。
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class ErrorMethod {
@ExceptionHandler(ArithmeticException.class)
public String error() {
System.out.println("error!");
return "error";
}
}