自定义异常
自定义异常
XDException
src/main/java/net/xdclass/online_xdclass/exception/XDException.java
1package net.xdclass.online_xdclass.exception;
2
3
4import net.xdclass.online_xdclass.utils.JsonData;
5import org.slf4j.Logger;
6import org.slf4j.LoggerFactory;
7import org.springframework.web.bind.annotation.ControllerAdvice;
8import org.springframework.web.bind.annotation.ExceptionHandler;
9import org.springframework.web.bind.annotation.ResponseBody;
10
11/**
12 * 异常处理类
13 */
14@ControllerAdvice
15public class CustomExceptionHandler {
16
17
18 private final static Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class);
19
20
21 @ExceptionHandler(value = Exception.class)
22 @ResponseBody
23 public JsonData handle(Exception e){
24
25 logger.error("[ 系统异常 ]{}",e);
26
27 if( e instanceof XDException ){
28
29 XDException xdException = (XDException) e;
30
31 return JsonData.buildError(xdException.getCode(),xdException.getMsg());
32
33 }else {
34
35 return JsonData.buildError("全局异常,未知错误");
36
37 }
38
39
40 }
41
42}
43
异常处理器
src/main/java/net/xdclass/online_xdclass/exception/CustomExceptionHandler.java
1package net.xdclass.online_xdclass.exception;
2
3
4import net.xdclass.online_xdclass.utils.JsonData;
5import org.slf4j.Logger;
6import org.slf4j.LoggerFactory;
7import org.springframework.web.bind.annotation.ControllerAdvice;
8import org.springframework.web.bind.annotation.ExceptionHandler;
9import org.springframework.web.bind.annotation.ResponseBody;
10
11/**
12 * 异常处理类
13 */
14@ControllerAdvice
15public class CustomExceptionHandler {
16
17
18 private final static Logger logger = LoggerFactory.getLogger(CustomExceptionHandler.class);
19
20
21 @ExceptionHandler(value = Exception.class)
22 @ResponseBody
23 public JsonData handle(Exception e){
24
25 logger.error("[ 系统异常 ]{}",e);
26
27 if( e instanceof XDException ){
28
29 XDException xdException = (XDException) e;
30
31 return JsonData.buildError(xdException.getCode(),xdException.getMsg());
32
33 }else {
34
35 return JsonData.buildError("全局异常,未知错误");
36
37 }
38
39
40 }
41
42}
43