原本的写法是返回了字符串
然后前端接收到的就是一个字符串,试着用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;
    }
}

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-01
  • 2022-03-03
  • 2022-12-23
  • 2021-07-30
  • 2022-12-23
  • 2021-09-09
猜你喜欢
  • 2022-12-23
  • 2021-10-09
  • 2022-12-23
  • 2022-12-23
  • 2022-01-13
  • 2022-12-23
  • 2021-10-01
相关资源
相似解决方案