Java全局异常捕获

java异常的捕获总共需要三个类
1.返回类
2.自定义异常类
3.全局异常捕获类
其他自行导入包

public class ResponseResult<T> {
    private static final long serialVersionUID = 1L;
    private Integer code;
    private String msg;
    private T data;
    /**
     * 状态码
     */
    public static final String CODE_TAG = "code";

    /**
     * 返回内容
     */
    public static final String MSG_TAG = "msg";

    /**
     * 数据对象
     */
    public static final String DATA_TAG = "data";

    /**
     * 初始化一个新创建的 ResponseResult 对象,使其表示一个空消息。
     */
    public ResponseResult() {
    }
    public ResponseResult(String msg) {
        this.msg = msg;
    }

    /**
     * 初始化一个新创建的 ResponseResult 对象
     *
     * @param code 状态码
     * @param msg  返回内容
     */
    public ResponseResult(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    /**
     * 初始化一个新创建的 ResponseResult 对象
     *
     * @param code 状态码
     * @param msg  返回内容
     * @param data 数据对象
     */
    public ResponseResult(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    /**
     * 返回成功消息
     *
     * @return 成功消息
     */
    public static <T> ResponseResult<T> success() {
        return ResponseResult.success("操作成功");
    }

    /**
     * 返回成功数据
     *
     * @return 成功消息
     */
    public static <T> ResponseResult<T>  success(T data) {
        return ResponseResult.success("操作成功", data);
    }

    /**
     * 返回成功消息
     *
     * @param msg 返回内容
     * @return 成功消息
     */
    public static <T> ResponseResult<T> success(String msg) {
        return ResponseResult.success(msg, null);
    }

    /**
     * 返回成功消息
     *
     * @param msg  返回内容
     * @param data 数据对象
     * @return 成功消息
     */
    public static <T> ResponseResult<T> success(String msg, T data) {
        return new ResponseResult<>(HttpStatus.SUCCESS, msg, data);
    }

    /**
     * 返回错误消息
     *
     * @return 失败消息
     */
    public static <T> ResponseResult<T> error() {
        return ResponseResult.error("操作失败");
    }

    /**
     * 返回错误消息
     *
     * @param msg 返回内容
     * @return 警告消息
     */
    public static <T> ResponseResult<T> error(String msg) {
        return ResponseResult.error(msg, null);
    }

    /**
     * 返回错误消息
     *
     * @param msg  返回内容
     * @param data 数据对象
     * @return 警告消息
     */
    public static <T> ResponseResult<T> error(String msg, T data) {
        return new ResponseResult<>(HttpStatus.ERROR, msg, data);
    }

    /**
     * 返回错误消息
     *
     * @param code 状态码
     * @param msg  返回内容
     * @return 警告消息
     */
    public static<T> ResponseResult<T> error(int code, String msg) {
        return new ResponseResult<>(code, msg, null);
    }


public class BusinessException extends RuntimeException {
    private int code;
    private String msg;
    public BusinessException() {
        super();
    }

    public BusinessException(String msg) {
        super(msg);
        this.msg = getMsg();
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    @Override
    public String toString() {
        return msg;
    }
@Slf4j
@ResponseBody
@RestControllerAdvice
public class GlobalExceptionHandler {
    public final Logger logger = LoggerFactory.getLogger(this.getClass());

    public GlobalExceptionHandler() {
    }

    public void doSomething(Exception e, HttpServletRequest request) {
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({HttpMessageNotReadableException.class})
    public ResponseResult handleHttpMessageNotReadableException(Exception e, HttpServletRequest request) {
        this.doSomething(e, request);
        this.logger.warn("400-参数解析失败,{},{}", e.getMessage(), request.getServletPath());
        return ResponseResult.error("参数解析失败");
    }

    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public ResponseResult handleHttpRequestMethodNotSupportedException(Exception e, HttpServletRequest request) {
        this.doSomething(e, request);
        this.logger.warn("405-不支持当前请求方法,{},{}", e.getMessage(), request.getServletPath());
        return ResponseResult.error("不支持当前请求方法");
    }

    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler({HttpMediaTypeNotSupportedException.class})
    public ResponseResult handleHttpMediaTypeNotSupportedException(Exception e, HttpServletRequest request) {
        this.doSomething(e, request);
        this.logger.warn("415-不支持当前媒体类型,{},{}", e.getMessage(), request.getServletPath());
        return ResponseResult.error("不支持当前媒体类型");
    }

    @ExceptionHandler({Exception.class})
    public ResponseResult handleException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        this.doSomething(e, request);
        if (e instanceof BusinessException) {
            if (e.getCause() == null) {
                this.logger.warn("业务提示,{},{}", e.getMessage(), request.getServletPath());
                response.setStatus(200);
            } else {
                this.logger.error("业务异常," + request.getServletPath(), e);
                response.setStatus(500);
            }

            return ResponseResult.error(e.getMessage());
        } else {
            this.logger.error("系统异常," + request.getServletPath(), e);
            response.setStatus(500);
            return ResponseResult.error("系统异常");
        }
    }

}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ChangeXuan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值