-
这篇搞一个全局异常构造体
-
主要目的是当代码报错时有个友好的提示,并且能更具自定义的报错信息快速确定BUG
-
代码不多就两个类,不多说,看代码
package org.meichao.config;
public class GlobalException extends Exception {
private int errorCode;
public GlobalException() {
}
public GlobalException(String message) {
super(message);
}
public GlobalException(String message, int errorCode) {
super(message);
this.errorCode = errorCode;
}
public int getErrorCode() {
return errorCode;
}
public void setErrorCode(int errorCode) {
this.errorCode = errorCode;
}
}
package org.meichao.config;
import org.meichao.constants.Constants;
import org.meichao.utils.RespInfoUtils;
import org.meichao.utils.vo.RespInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
/**
* 定义全局异常处理类
* @ControllerAdvice 捕获所有Controller中抛出的异常
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理Exception异常,返回json结果
* @ExceptionHandler 启动应用后,处理@RequestMapping注解的方法上
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public RespInfo<String> defaultErrorHandler(HttpServletRequest request,Exception e){
logger.info("================》全局异常:",e);
return RespInfoUtils.create()
.respFailure(e instanceof GlobalException ? e.getMessage() : "系统错误,请重试").toRespInfo();
}
}
-
return里返回的是返回信息工具类(有兴趣的可以去SpringBoot简单多模块框架搭建(3)---返回信息构造体观看)
-
测试一波
package org.meichao.hello.controller;
import org.meichao.config.GlobalException;
import org.meichao.hello.service.HelloService;
import org.meichao.utils.RespInfoUtils;
import org.meichao.utils.vo.RespInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
public class HelloController {
private Logger logger = LoggerFactory.getLogger(HelloController.class);
@Autowired
private HelloService helloService;
@RequestMapping("/hello")
public RespInfo hello() throws GlobalException {
try {
System.out.println(10/0);
}catch (Exception e){
throw new GlobalException("水水水水水水水");
}
return RespInfoUtils.create().respSuccess(helloService.getUser()).toRespInfo();
}
}
-
完结撒花