Spring MVC处理异常

一、将异常映射为HTTP状态码

1.1 spring异常与HTTP状态码

Spring异常HTTP状态码
BindException400 - Bad Request
ConversionNotSupportedException500 - Internal Server Error
HttpMediaTypeNotAcceptableException406 - Not Acceptable
HttpMediaTypeNotSupportedException415 - Unsupported Media Type
HttpMessageNotReadableException400 - Bad Request
HttpMessageNotWritableException500 - Internal Server Error
HttpRequestMethodNotSupportedException405 - Method Not Allowed
MethodArgumentNotValidException400 - Bad Request
MissingServletRequestParameterException400 - Bad Request
MissingServletRequestPartException400 - Bad Request
NoSuchRequestHandlingMethodException404 - Not Found
TypeMismatchException400 - 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";
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

书香水墨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值