# 全局异常捕获

# @Import导入

使用该方法时,我们需要引入该依赖。QmExceptionHandler

@Import({
    QmFrameworkApplication.class,
    QmExceptionHandler.class
})
1
2
3
4

引入该类后,当我们的服务出现异常时,返回给前端的信息将会变成如下样式。

{
    "value": {
        "msg": "服务器开小猜啦",
        "code": 500,
        "data": null,
        "responseTime": 1559378488942
    }
}
1
2
3
4
5
6
7
8

# 源码

@ControllerAdvice
@Controller
@RequestMapping(value = "/error")
public class QmExceptionHandler extends QmController {

    private static final Logger LOG = LoggerFactory.getLogger(QmExceptionHandler.class);

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public String httpRequestMethodNotSupportedException(HttpServletResponse response,
                                                         Exception e) {
        LOG.info("请求方式错误,请核实请求方式 `GET` and `POST`");
        response.setStatus(200);
        return super.sendJSON(QmCode._405);
    }

    @ExceptionHandler(QmParamNullException.class)
    @ResponseBody
    public String qmParamNullException(HttpServletResponse response,
                                       Exception e) {
        LOG.info("缺少某些请求参数,请核实请求参数是否正确!");
        e.printStackTrace();
        response.setStatus(200);
        return super.sendJSON(QmCode._100);
    }

    @ExceptionHandler(QmParamErrorException.class)
    @ResponseBody
    public String qmParamErrorException(HttpServletResponse response,
                                        Exception e) {
        LOG.info("请求参数错误,请核实请求参数是否正确!");
        response.setStatus(200);
        return super.sendJSON(QmCode._101);
    }

    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseBody
    public String httpMediaTypeNotSupportedException(HttpServletResponse response,
                                                     Exception e) {
        response.setStatus(200);
        return super.sendJSON(QmCode._415);
    }


    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    @ResponseBody
    public String notFoundPage404(HttpServletResponse response,
                                  Exception e) throws IOException {
        LOG.info("请求地址错误,请核实请求地址是否正确!");
        response.setStatus(200);
        return super.sendJSON(QmCode._404);
    }


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String defaultException(HttpServletResponse response, Exception e) throws IOException {
        LOG.info("服务器遇到了错误,请检查相关问题!");
        e.printStackTrace();
        response.setStatus(200);
        return super.sendJSON(QmCode._500);
    }

}
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

# 说明

您可以清晰的看到,它使用了@ControllerAdvice@Controller来标注该类为功能型类。

而我们在这里捕获了/error,使所有发生异常的情况都可以在该类进行捕捉。

在每个方法头部标注@ExceptionHandler可以对指定的异常进行捕获。

最近更新: 2019/10/17 上午4:20:42