全局异常处理

全局异常处理,第1张

阿松大

构架截图

 result.java

package com.qgx.demo.common;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 接口统一返回包装类
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result {

    private String code;
    private String msg;
    private Object data;

    public static Result success() {
        return new Result(Constants.CODE_200, "", null);
    }

    public static Result success(Object data) {
        return new Result(Constants.CODE_200, "", data);
    }

    public static Result error(String code, String msg) {
        return new Result(code, msg, null);
    }

    public static Result error() {
        return new Result(Constants.CODE_500, "系统错误", null);
    }

}

Constants.java(常量类,定义Code) 接口

package com.qgx.demo.common;

/**
 * @author:ERA
 */
public interface Constants {
    String CODE_200 = "200"; //成功
    String CODE_401 = "401";  // 权限不足
    String CODE_400 = "400";  // 参数错误
    String CODE_500 = "500"; // 系统错误
    String CODE_600 = "600"; // 其他业务异常
    String Session_key="";
}

GlobalExceptionHandler.java

package com.qgx.demo.exception;

import com.qgx.demo.common.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author:ERA
 * ControllerAdvice:异常集中处理,更好的使业务逻辑与异常处理剥离开;其是对Controller层进行拦截
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 如果抛出的的是ServiceException,则调用该方法
     * @param se 业务异常
     * @return Result
     */
    //ExceptionHandler 统一处理某一类异常
    @ExceptionHandler(value = ServiceException.class)
    @ResponseBody
    public Result handle(ServiceException se){
        return Result.error(se.getCode(), se.getMessage());
    }
}

ServiceException.java(自定义业务异常)

package com.qgx.demo.exception;

import lombok.Getter;

/**
 * @author:ERA
 * @Description: 自定义异常
 */
@Getter
    public class ServiceException extends RuntimeException{
        private String code;

        public ServiceException(String code, String msg) {
            super(msg);
            this.code = code;
        }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/923366.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存