houzhongjian
2024-11-07 a874b928e16320839315b9abcdf2cece1229a424
提交 | 用户 | 时间
e7c126 1 package com.xxl.job.admin.controller.resolver;
H 2
3 import com.xxl.job.admin.core.exception.XxlJobException;
4 import com.xxl.job.core.biz.model.ReturnT;
5 import com.xxl.job.admin.core.util.JacksonUtil;
6 import org.slf4j.Logger;
7 import org.slf4j.LoggerFactory;
8 import org.springframework.stereotype.Component;
9 import org.springframework.web.bind.annotation.ResponseBody;
10 import org.springframework.web.method.HandlerMethod;
11 import org.springframework.web.servlet.HandlerExceptionResolver;
12 import org.springframework.web.servlet.ModelAndView;
13
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 import java.io.IOException;
17
18 /**
19  * common exception resolver
20  *
21  * @author xuxueli 2016-1-6 19:22:18
22  */
23 @Component
24 public class WebExceptionResolver implements HandlerExceptionResolver {
25     private static transient Logger logger = LoggerFactory.getLogger(WebExceptionResolver.class);
26
27     @Override
28     public ModelAndView resolveException(HttpServletRequest request,
29             HttpServletResponse response, Object handler, Exception ex) {
30
31         if (!(ex instanceof XxlJobException)) {
32             logger.error("WebExceptionResolver:{}", ex);
33         }
34
35         // if json
36         boolean isJson = false;
37         if (handler instanceof HandlerMethod) {
38             HandlerMethod method = (HandlerMethod)handler;
39             ResponseBody responseBody = method.getMethodAnnotation(ResponseBody.class);
40             if (responseBody != null) {
41                 isJson = true;
42             }
43         }
44
45         // error result
46         ReturnT<String> errorResult = new ReturnT<String>(ReturnT.FAIL_CODE, ex.toString().replaceAll("\n", "<br/>"));
47
48         // response
49         ModelAndView mv = new ModelAndView();
50         if (isJson) {
51             try {
52                 response.setContentType("application/json;charset=utf-8");
53                 response.getWriter().print(JacksonUtil.writeValueAsString(errorResult));
54             } catch (IOException e) {
55                 logger.error(e.getMessage(), e);
56             }
57             return mv;
58         } else {
59
60             mv.addObject("exceptionMsg", errorResult.getMsg());
61             mv.setViewName("/common/common.exception");
62             return mv;
63         }
64     }
65     
66 }