@RequestMapping("test/run/old")
public JsonResponse testRunOld() {
try {
exampleService.runTest();
System.out.println("正常运行");
return JsonResponse.newOk();
}catch (DataNotCompleteException e) {
logger.error("something error occured!");
return JsonResponse.newError(ErrorMsgEnum.DATA_NO_COMPLETE);
} catch (Exception e) {
return JsonResponse.newError();
}
}
@Controller
public class TestController {
@Autowired
private IExampleService exampleService;
@RequestMapping("test/run/aop")
public JsonResponse testRunAop() throws Exception {
exampleService.runTest();
System.out.println("正常运行");
return JsonResponse.newOk();
}
}
@Service
public class ExampleService implements IExampleService{
@Override
public void runTest() throws Exception {
// do something
System.out.println("run something");
throw new CustomException(ErrorMsgEnum.DATA_NO_COMPLETE);
}
}
public enum ErrorMsgEnum {
//正常返回的枚举
SUCCESS(true, 2000,"正常返回", "操作成功"),
// 系统错误,50开头
SYS_ERROR(false, 5000, "系统错误", "亲,系统出错了哦~"),
PARAM_INVILAD(false, 5001, "参数出现异常", "参数出现异常"),
DATA_NO_COMPLETE(false, 5002, "数据填写不完整,请检查", "数据填写不完整,请检查");
private ErrorMsgEnum(boolean ok, int code, String msg ,String userMsg) {
this.ok = ok;
this.code = code;
this.msg = msg;
this.userMsg = userMsg;
}
private boolean ok;
private int code;
private String msg;
private String userMsg;
}
public class JsonResponse{
String msg;
Object data;
public JsonResponse() {
msg = "";
data = null;
}
public static JsonResponse newOk() {
JsonResponse response = new JsonResponse();
response.setState(State.newOk());
return response;
}
public static JsonResponse newOk(Object data) {
JsonResponse response = new JsonResponse();
response.setData(data);
response.setState(State.newOk());
return response;
}
public static JsonResponse newError() {
JsonResponse response = new JsonResponse();
response.setMsg("无情的系统异常!");
return response;
}
public static JsonResponse newError(ErrorMsgEnum errorMsgEnum) {
JsonResponse response = new JsonResponse();
state.setMsg(errorMsgEnum.getErrorMsg());
return response;
}
}
public class CustomException extends Exception {
private ErrorMsgEnum errorMsgEnum;
public CustomException(ErrorMsgEnum errorMsgEnum) {
this.errorMsgEnum = errorMsgEnum;
}
}
@Around("execution(public * com.jason.*.controller..*.*(..))")
public JsonResponse serviceAOP(ProceedingJoinPoint pjp) throws Exception {
JsonResponse newResultVo = null;
try {
return (JsonResponse) pjp.proceed();
} catch (CustomException e) {
logger.info("自定义业务异常:" + e.getMessage());
ErrorMsgEnum errorMsgEnum = e.getErrorMsgEnum();
if (Objects.nonNull(errorMsgEnum)) {
newResultVo = JsonResponse.newError(errorMsgEnum);
} else {
newResultVo = JsonResponse.newError(e.getMessage());
}
} catch (Exception e) {
//可以顺便处理你的日志,此处能取到方法名,参数等等
logger.error("出现运行时异常:", e);
newResultVo = JsonResponse.newError();
}
return newResultVo;
}
至此,我们已经可以直接在 Service 或 Controller 中随意抛出一个异常,
直接每个控制器方法抛出的异常定义为 throws Exception 即可
github地址:https://github.com/JasonFirst/exceptionHandler