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