Skip to content

Commit dabe3e4

Browse files
committed
feat: 添加全局的异常处理类,实现 ErrorContoller 对 404 异常定制返回内容
1 parent 9b5f231 commit dabe3e4

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package info.cadecode.simple.common.exception;
2+
3+
import info.cadecode.simple.common.response.SimpleRes;
4+
import info.cadecode.simple.constant.ReasonEnum;
5+
import org.slf4j.Logger;
6+
import org.slf4j.LoggerFactory;
7+
import org.springframework.boot.web.servlet.error.ErrorController;
8+
import org.springframework.http.converter.HttpMessageNotReadableException;
9+
import org.springframework.web.bind.MethodArgumentNotValidException;
10+
import org.springframework.web.bind.annotation.*;
11+
12+
import javax.servlet.http.HttpServletResponse;
13+
14+
/**
15+
* @author Cade Li
16+
* @date 2021/7/16
17+
* @description: 统一异常处理类
18+
*/
19+
@RestController
20+
@ControllerAdvice(basePackages = {"info.cadecode.simple.controller"})
21+
public class SimpleExceptionHandler implements ErrorController {
22+
23+
private final Logger log = LoggerFactory.getLogger(this.getClass());
24+
25+
/**
26+
* 处理 SimpleException
27+
*/
28+
@ExceptionHandler(value = SimpleException.class)
29+
@ResponseBody
30+
public SimpleRes handleSimpleException(SimpleException e, HttpServletResponse response) {
31+
log.error("SimpleException Handler =>", e);
32+
response.setStatus(e.getCode());
33+
return SimpleRes.exception(e);
34+
}
35+
36+
/**
37+
* 处理一般异常
38+
*/
39+
@ExceptionHandler(value = Exception.class)
40+
@ResponseBody
41+
public SimpleRes handleOtherException(Exception e, HttpServletResponse response) {
42+
log.error("Exception Handler =>", e);
43+
if (e instanceof HttpMessageNotReadableException) {
44+
response.setStatus(ReasonEnum.NOT_FIT.getCode());
45+
return SimpleRes.reason(ReasonEnum.NOT_FIT).data(e.getMessage());
46+
}
47+
response.setStatus(ReasonEnum.ERROR.getCode());
48+
return SimpleRes.reason(ReasonEnum.ERROR).data(e.getMessage());
49+
}
50+
51+
/**
52+
* 处理 404 错误(实现 ErrorController 接口)
53+
*/
54+
@RequestMapping("${server.error.path:${error.path:/error}}")
55+
public SimpleRes handleError(HttpServletResponse response) {
56+
response.setStatus(ReasonEnum.NOT_EXIT.getCode());
57+
return SimpleRes.reason(ReasonEnum.NOT_EXIT);
58+
}
59+
}

0 commit comments

Comments
 (0)