java接口报错500自定义异常信息返回


import com.sun.java.browser.plugin2.liveconnect.v1.Result;
import com.techno.util.ResponseData;
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;

/**
 * 捕获异常的类,返回信息给浏览器,可以自定义返回的code,msg等信息
 */
@ControllerAdvice
public class ExceptionHandle {
    private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseData handle(Exception e) {
        ResponseData res = ResponseData.serverInternalError();
        if (e instanceof OwnException) {   //判断异常是否是我们定义的异常
            OwnException ownException = (OwnException) e;
            return res.putDataValue(ownException.getCode()+"", ownException.getMessage());
        }else {
            logger.error("【系统异常】{}", e);
            return res.putDataValue("-1", "系统异常");
        }
    }
}

class OwnException extends RuntimeException{    //注意:spring中,只有RuntimeException才会进行事务回滚,Exception不会进行事务回滚

    private Integer code;

    public OwnException(ResultEnum resultEnum) {
        super(resultEnum.getMsg());
        this.code = resultEnum.getCode();
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}


enum ResultEnum {
    UNKONW_ERROR(-1, "未知错误"),
    SERVER_ERROR(500,"系统异常"),
    SUCCESS(0, "成功"),
    ;

    private Integer code;

    private String msg;

    ResultEnum(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public Integer getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}


@ControllerAdvice会拦截系统controller或service抛出的异常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值