GlobalExceptionHandler.java
1.54 KB
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
package com.uccc.log.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.uccc.log.exception.ApiException;
import com.uccc.pretty.constants.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author :bert
* @date :2021-09-10 10:17.
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(Exception.class)
public void defaultErrorHandler(HttpServletRequest req, HttpServletResponse response, Exception e) throws Exception {
log.debug("Handler exception:{}", e.toString());
int code = ErrorCode.SERVER_ERROR.getCode();
String message = ErrorCode.SERVER_ERROR.getMessage();
if (e instanceof ApiException) {
code = ((ApiException) e).getCode();
message = ((ApiException) e).getReason();
}
req.setAttribute("errorCode", code);
req.setAttribute("errorMessage", message);
response.setContentType("application/json;charset=utf-8");
JSONObject result = new JSONObject();
result.put("code", code);
result.put("message", message);
response.getWriter().write(result.toJSONString());
if (code == ErrorCode.SERVER_ERROR.getCode()) log.info("Handler unknown exception:", e);
}
}