@ControllerAdvice
@Slf4j
public class MyExceptionHandler {
Integer code = RespCode.RespEnum.SYSERROR_PERMISSIONS_403.getCode();
String message = RespCode.RespEnum.SYSERROR_PERMISSIONS_403.getDescribe();
@ExceptionHandler(BizException.class)
public String handlerBizException(BizException e, HttpServletRequest request, HttpServletResponse response){
log.debug("MyExceptionHandler.handlerBizException>>>>>>>>>>>>>>>>>>>>>>>>>>");
//此处使用对象或map集合均可以
RespData bizException = new RespData();
bizException .setRespInfo(false,code, message);
// Map<String,Object> bizException = new HashMap<>();
// bizException .put("code",e.getCode());
// bizException .put("message",e.getMessage());
request.setAttribute("bizException ",bizException );
// request.setAttribute("javax.servlet.error.status_code",500);
request.setAttribute("javax.servlet.error.status_code",e.getCode());
// 判断请求类型是否为Ajax请求
String header = request.getHeader("X-Requested-With");
boolean isAjax = "XMLHttpRequest".equalsIgnoreCase(header);
if(isAjax){
JSONObject object = new JSONObject();
object.put("code", e.getCode());
object.put("message", e.getMessage());
this.returnJson(response, object.toJSONString());
}
//转发到/error
return "forward:/error";
}
private void returnJson(HttpServletResponse response, String json) {
PrintWriter writer = null;
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=utf-8");
try {
writer = response.getWriter();
writer.print(json);
} catch (IOException e) {
} finally {
if (writer != null)
writer.close();
}
}
}
@Component
@Slf4j
public class MyErrorAttributes extends DefaultErrorAttributes {
//返回值的map就是页面和json能获取的所有字段
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
log.debug("MyErrorAttributes.getErrorAttributes>>>>>>>>>>>>>>>>>>>>>>>>>>");
Map<String, Object> errorAttributesMap=super.getErrorAttributes(webRequest, includeStackTrace);
//添加需要返回的信息
//异常处理器携带的数据 ,注意当bizException在页面获取不到值时,会再次发出请求
Object bizException = webRequest.getAttribute("bizException",0);
if(StringUtil.isObjectNotEmpty(bizException))
errorAttributesMap.put("bizException",bizException);
return errorAttributesMap;
}
}
@ResponseBody
@RequestMapping("/hello")
public String hello(@RequestParam("user") String user){
if(user.equals("aa")){
try{
int a=0/0;
}catch (Exception e){
throw new BizException("502","测试111");
// throw new BizLoginException("501","测试登录111");
}
}
return "hello world test";
}
http://127.0.0.1:8080/sys/hello?user=aa
springboot统一异常处理
最新推荐文章于 2024-10-20 11:22:44 发布
本文介绍了一个Spring Boot应用中自定义异常处理和错误属性的方法。通过@ControllerAdvice注解的MyExceptionHandler类处理BizException异常,返回特定的HTTP状态码和错误信息。同时,通过自定义MyErrorAttributes类,增强错误信息的细节,使其更易于理解和调试。
1539

被折叠的 条评论
为什么被折叠?



