springboot统一异常处理怎么返回json对象给前端

原本的写法是返回了字符串
然后前端接收到的就是一个字符串,试着用json.parse方式没解决。就只能从后端入手,直接返回json
这里要加上responsebody注解,把对象封装成json

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value = ServiceException.class)
    public String handleCustomException(Throwable e){
        ResultMsg resultMsg = new ResultMsg();
        resultMsg.setMsg(e.getMessage());
        if (e instanceof EmptyArgumentException){
            resultMsg.setCode(ResultCode.PARAMS_IS_NULL);
        }else if (e instanceof InsertException){
            resultMsg.setCode(ResultCode.INSERT_FAIL);
        }else if (e instanceof UpdateException){
            resultMsg.setCode(ResultCode.UPDATE_FAIL);
        }

        return new Gson.toJson(resultMsg.toString()); // 也就是返回了一个字符串格式
    }
}

修改后的写法,直接返回实体类对象

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(value = ServiceException.class)
    public ResultMsg handleCustomException(Throwable e){
        ResultMsg resultMsg = new ResultMsg();
        resultMsg.setMsg(e.getMessage());
        if (e instanceof EmptyArgumentException){
            resultMsg.setCode(ResultCode.PARAMS_IS_NULL);
        }else if (e instanceof InsertException){
            resultMsg.setCode(ResultCode.INSERT_FAIL);
        }else if (e instanceof UpdateException){
            resultMsg.setCode(ResultCode.UPDATE_FAIL);
        }

        return resultMsg;
    }
}
posted @ 2021-05-11 21:49  张三丰学Java  阅读(1055)  评论(0编辑  收藏  举报