springmvc学习笔记(30)——@ResponseStatus注解处理异常

一、ResponseStatus修饰类

ResponseStatus注解的使用非常简单,我们创建一个异常类,加上注解

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value=HttpStatus.FORBIDDEN,reason="用户不匹配")
public class UserNotMatchException extends RuntimeException{


}
  • ResponseStatus注解是修饰类的

          value:value属性是http状态码,比如404,500等

          reason:是错误信息

 写一个目标方法抛出该异常

@RequestMapping("/testResponseStatus")
    public String testResponseStatus(int i){
        if(i==0)
            throw new UserNotMatchException();
        return "hello";
    }

当传入参数i==0的时候将抛异常。下图是效果图 

使用了ResponseStatus注解之后,用户看到的异常界面正是我们自己定义的异常,而不再是一大堆用户看不懂的代码。

二、ResponseStatus修饰方法

ResponseStatus如果修饰目标方法,将会发生什么事。

@ResponseStatus(value=HttpStatus.FORBIDDEN,reason="用户名不匹配")
    @RequestMapping("/testResponseStatus")
    public String testResponseStatus(int i){
        if(i==0)
            throw new UserNotMatchException();
        return "hello";
    }

 

  • 仔细看这张结果图中的访问路径,我传入的参数是i=1,正常来说是不应该抛异常的,可是它抛了。。它真的抛了。。
  • 结论:ResponseStatus修饰目标方法,无论它执行方法过程中有没有异常产生,用户都会得到异常的界面。而目标方法正常执行
扫描二维码关注公众号,回复: 4510770 查看本文章

猜你喜欢

转载自blog.csdn.net/qq_36826506/article/details/84996407