TangCheng
6 天以前 47fc68b2894ee24d6b98675f98829e648b42ace8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package com.smtservlet.exception;
 
import java.util.Map;
import java.util.Map.Entry;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
 
import com.smtservlet.core.SMTApp;
import com.smtservlet.util.Json;
import com.smtservlet.util.SMTJsonWriter;
import com.smtservlet.util.SMTStatic;
 
/**
 * 当请求发生异常时,自动返回异常信息View的类 
 */
public class SMTControlExceptionResolver implements HandlerExceptionResolver 
{
    private static class ExceptionView implements View
    {
        String _errCode;
        String _msg;
        String _url;
        
        public ExceptionView(String errCode, String msg, String url)
        {
            _errCode = errCode;
            _msg = msg;
            _url = url;
        }
        
        @Override
        public String getContentType() {
            return null;
        }
 
        @Override
        public void render(Map<String, ?> paramMap,
                HttpServletRequest request,
                HttpServletResponse response) throws Exception {
            
//            if(request.getMethod().equalsIgnoreCase("GET"))
//            {
//                response.setCharacterEncoding("UTF-8");
//                response.setContentType("text/html;charset=UTF-8");
//                response.getOutputStream().write(_msg.getBytes("UTF-8"));
//            }
//            else
            {
                if(_url != null)
                {
                    response.setCharacterEncoding("UTF-8");
                    SMTJsonWriter jsonWr = new SMTJsonWriter(false);
                    jsonWr.addKeyValue("json_ok", false);
                    jsonWr.addKeyValue("err_code", _errCode);
                    jsonWr.addKeyValue("err_no_login", "AUTH".equals(_errCode));
                    jsonWr.addKeyValue("err_to_local", true);
                    jsonWr.addKeyValue("json_top_url", _url);
                    if(_msg != null)
                        jsonWr.addKeyValue("json_msg", _msg);
                    String ret = jsonWr.getFullJson();
                    response.getOutputStream().write(ret.getBytes("UTF-8"));
                }
                else if(_msg != null)
                {
                    response.setCharacterEncoding("UTF-8");
                    SMTJsonWriter jsonWr = new SMTJsonWriter(false);
                    jsonWr.addKeyValue("json_ok", false);
                    jsonWr.addKeyValue("err_no_login", true);
                    jsonWr.addKeyValue("err_to_local", true);
                    jsonWr.addKeyValue("json_msg", "内部错误:" + _msg);
                    String ret = jsonWr.getFullJson();
                    response.getOutputStream().write(ret.getBytes("UTF-8"));
                }
            }
        }
    }
 
    private static  Logger _logger = LogManager.getLogger(SMTControlExceptionResolver.class);
    
    @Override
    public ModelAndView resolveException(
            final HttpServletRequest request,
            HttpServletResponse response, 
            Object paramObject,
            Exception paramException) {
        Json jsonConfig = SMTStatic.emptyObject;
        
        ModelAndView view = null;
        String urlHome = SMTApp.getRequestExeptionUrl();
        if(SMTStatic.isNullOrEmpty(urlHome))
            urlHome = "{WEB_ROOT}";
        
        StringBuilder sbLog = new StringBuilder();
        if(request != null)
        {
            String queryString = request.getQueryString();
            sbLog.append(String.format(
                    "\n\n========================================\nReqURL:%s:%s%s\n", 
                    request.getMethod(), 
                    request.getRequestURL(), 
                    queryString== null ? "" : "?" + queryString));
            
            Map<String, String[]>  map = request.getParameterMap();
            
            for(Entry<String, String[]>  ent : map.entrySet())
            {
                String keys = ent.getKey().toString();
                String values = ((String[])ent.getValue())[0];
                sbLog.append(String.format("ReqPara:%s=%s\n", keys, values));
            }
            _logger.fatal(SMTStatic.throwToString(paramException) + sbLog.toString());
        }
        else
        {
            _logger.fatal(SMTStatic.throwToString(paramException));
        }
        
//        if(request.getMethod().equalsIgnoreCase("GET"))
//        {
//            // 如果当前是子窗口,则显示系统信息
//            if(!SMTStatic.isNullOrEmpty(request.getHeader("Referer")))
//            {
//                if(paramException instanceof SMTAuthorityException)
//                {
//                    view = new ModelAndView(new ExceptionView("AUTH", jsonConfig.safeGetStr("no_authority", "您无权使用此项功能,请重新登录"), null));
//                }
//            }
//            // 如果当前是主窗口,则直接跳到登录页面
//            else
//            {
//                urlHome = SMTStatic.stringFormat(urlHome, new SMTStatic.StringNamedNotify(){
//
//                    @Override
//                    public Object getNamedValue(String name, Object[] args) throws Exception {
//                        if(name.equals("WEB_ROOT"))
//                            return "/";
//                        throw new Exception("unsupport url argument : " + name);
//                    }
//                    
//                });
//                
//                view = new ModelAndView("redirect:" + urlHome);
//            }
//        }
//        else
        {
            urlHome = SMTStatic.stringFormat(urlHome, new SMTStatic.StringNamedNotify(){
 
                @Override
                public Object getNamedValue(String name, Object[] args) throws Exception {
                    if(name.equals("WEB_ROOT"))
                        return request.getContextPath() + "/";
                    throw new Exception("unsupport url argument : " + name);
                }
                
            });
            
            if(paramException instanceof SMTAuthorityException)
            {
                view = new ModelAndView(new ExceptionView("AUTH", jsonConfig.safeGetStr("no_authority", "您无权使用此项功能,请重新登录"), urlHome));
            }
            else
            {
                String uuid = SMTStatic.newSequence();
                _logger.fatal("exception log id : " + uuid, paramException);
                view = new ModelAndView(new ExceptionView("EXCEPTION", jsonConfig.safeGetStr("inner_exception", "发生内部错误。" + SMTStatic.throwToString(paramException)), urlHome));
            }
        }    
        return view;
    }
 
}