codecamp

Spring MVC 使用@ResponseStatus注解业务异常

业务异常可以使用@ResponseStatus来注解。当异常被抛出时,ResponseStatusExceptionResolver会设置相应的响应状态码。DispatcherServlet会默认注册一个ResponseStatusExceptionResolver 以供使用。

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

package com.zj.exception;
 
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
 
@ResponseStatus(value=HttpStatus.FORBIDDEN,reason="用户不匹配")
public class UserNotMatchException extends RuntimeException{
}
ResponseStatus注解是修饰类的
它有两个属性,value属性是http状态码,比如404,500等。reason是错误信息

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

@RequestMapping("/testResponseStatus")
public String testResponseStatus(int i){
    if(i==0)
        throw new UserNotMatchException();
    return "hello";
}
使用了ResponseStatus注解之后,用户看到的异常界面正是我们自己定义的异常,而不再是一大堆用户看不懂的代码。




Spring MVC 处理一般的异常
Spring MVC 对Servlet默认容器错误页面的定制化
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }