1.第一种
使用@ResponseStatus注解
先定义一个异常类
@ResponseStatus(code=HttpStatus.INTERNAL_SERVER_ERROR,reason="111")
public class ServerException extends Exception {
}
然后往出抛异常别捕获
@RequestMapping(value = "/user", method = RequestMethod.GET)
public String getUser(@RequestParam String userName) throws ServerException{
if(StringUtils.isEmpty(userName)){
throw new ServerException();
}
return "im zhangsan";
}
这样请求如果触发这个抛出的异常,就会返回自定义的状态码