xmtrock
发布于 2021-05-02 / 150 阅读
0

后端web中,结果封装、全局异常处理

因为是前后端分离,所以有必要统一一个结果返回封装类,这样子前后端交互的时候有统一的标准,约定相同的正常或异常返回信息规则。

@Data
public class RespBean implements Serializable {

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

    //成功方法构造
    public static RespBean succ(Integer code, String msg, Object data) {
        RespBean r = new RespBean();
        r.setCode(code);
        r.setMsg(msg);
        r.setData(data);
        return r;
    }
    public static RespBean succ(Object data) {
        return succ(200, "操作成功", data);
    }

    //失败方法构造
    public static RespBean fail(Integer code, String msg, Object data) {
        RespBean r = new RespBean();
        r.setCode(code);
        r.setMsg(msg);
        r.setData(data);
        return r;
    }
    public static RespBean fail(String msg) {
        return fail(400, msg, null);
    }
    public static RespBean fail() {
        return fail(400, "操作失败", null);
    }

    //创建方法
    public static RespBean build() {
        return new RespBean();
    }
}

测试:

@RestController
public class TestController {
    @Autowired
    SysUserService sysUserService;

    @GetMapping("/test")
    public RespBean test() {
        return RespBean.succ(sysUserService.list());
    }
}

结果:
20210502065538883
通过使用@ControlelrAdvice来进行全局统一异常处理
@Exception(value=RuntimeException.class)来针对性指定捕获的各个类型异常

@Slf4j
@RestControllerAdvice //因为异步
public class GlobalExceptionHandler {
    @ResponseStatus(HttpStatus.BAD_REQUEST) //这个记得要带上,不然浏览器不知道状态码
    @ExceptionHandler(value = RuntimeException.class)
    public RespBean handlerRuntimeException(RuntimeException e) {
        log.error("异常:{}", e.getMessage());
        return RespBean.fail(e.getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = IllegalArgumentException.class)//非法数据
    public RespBean handlerIllegalArgumentException(RuntimeException e) {
        log.error("异常:{}", e.getMessage());
        return RespBean.fail(e.getMessage());
    }
}

20210502071631393