SpringMvc 异常处理

使用场景

当使用Spring MVC进行Web开发的时候,对于异常可以进行集中式的处理

首先声明一个异常枚举类

public enum  ExceptionDesception {

    NO_PERMISSION(-1,"无权限");

    private int code;
    private String msg;

    ExceptionDesception(int code,String msg){
        this.code=code;
        this.msg=msg;
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}

方式1,使用继承或者实现接口的方式

a.声明一个BaseController用来集中处理异常

public class BaseController {

    @ExceptionHandler({WebApiException.class})
    @ResponseBody
    public Object expHandler(WebApiException e){
        return createResult(e);
    }

    public JSONObject createResult(BaseException e){
        JSONObject result=new JSONObject();
        result.put("code",e.getCode());
        result.put("msg",e.getMessage());
        return result;
    }
}

或者上将其声明为接口,同时方法使用 default修饰然后让Controller继承自该BaseController即可


方式2 使用 @ControllerAdvice 该注解来处理异常

@ControllerAdvice
public class BaseExceptionHandler {

    @ExceptionHandler({WebApiException.class})
    @ResponseBody
    public Object expHandler(WebApiException e){
        return createResult(e);
    }

    public JSONObject createResult(BaseException e){
        JSONObject result=new JSONObject();
        result.put("code",e.getCode());
        result.put("msg",e.getMessage());
        return result;
    }
}

通过方式2,controller并不需要实现或者继承就能做到异常处理,相对方式1更加解耦一些


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值