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