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;
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM