开发过程中由于出现异常时想要返返回指定类型的json串,springboot自带的异常处理无法满足需求,自己封装异常处理类进行指定的异常处理。
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
*统一处理拦截
*
*/
@ControllerAdvice//标识为controller异常处理类
public class ControllerExceptionHandler {
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//状态码500
@ExceptionHandler(UserException.class)//指定异常
public Map<String ,Object> UserNotExitException(UserException ue){
Map<String,Object> map = new HashMap<String,Object>();
map.put("id", ue.getId());
map.put("message", ue.getMessage());
return map;
}
}
自定义异常处理类
//自定义异常类
public class UserException extends RuntimeException{
private static final long serialVersionUID = 1L;
private String id;
private String message;
public UserException(String id, String message) {
super("this is user exception");
this.id = id;
this.message = message;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
运行时异常抛出
@JsonView(User.UserDetailView.class)//json视图处理器,博主下一篇文章解释,可注释掉
//@RequestMapping(value="/user/{id:\\d+}",method = RequestMethod.GET)//限制id只能为数字
@GetMapping("/{id:\\d+}")//正则表达式,限制传入内容只能为id
public User getInfo(@PathVariable(name="id") String thisId){//获取url中的指定id
User u = new User();
u.setUsername("1");
u.setPassword("11");
throw new UserException("1","我这出问题了");//抛出指定异常
//return u;
}
总结一下restful风格开发情况下,springboot2异常抛出时捕获处理顺序
controller -- aspec --- interceptor---filter