SpringBoot自定義404、500返回JSON資料
阿新 • • 發佈:2018-12-09
現有的方法,編寫全域性的異常處理,需要在SpringBoot配置檔案中配置沒有找到Controller時丟擲異常,並且將靜態資源對映關閉。因為預設是不丟擲異常的,是去找錯誤頁面,所以還需要關閉靜態資源對映。但是這樣就無法訪問靜態資源了。以下是解決方法。 當未找到頁面時,會呼叫預設的Controller,就是這個沒有值的RequestMapping。 在這個Controller中手動丟擲異常,實際這裡應該寫switch語句,根據不同的錯誤丟擲不同的異常,暫時沒時間改。 自定義預設Controller
@Controller
public class DefaultController {
@RequestMapping
public void error(HttpServletRequest request) throws NoHandlerFoundException {
throw new NoHandlerFoundException(request.getMethod(),request.getRequestURI(),new HttpHeaders());
}
}
在這裡編寫全域性的異常處理,使用自定義的返回結構返回資料。
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public String handlerException(Exception e) {
if (e instanceof NoHandlerFoundException) {
ResultBean resultBean = new ResultBean(DEV_CODE_NOTFOUND,DEV_MSG_RESOURCE_NOT_FOUND,LOCALE_MSG_RESOURCE_NOT_FOUND);
return resultBean.getResult();
}
else {
e.printStackTrace();
return new ResultBean(DEV_CODE_FAIL,e.getMessage(),LOCALE_MSG_SYSTEM_ERROR).getResult();
}
}
}
自定義JSON返回結構
public class ResultBean {
private int code;
private String devMsg;
private String msg;
private String data;
public ResultBean(int code, String devMsg, String msg, String data) {
this.code = code;
this.devMsg = devMsg;
this.msg = msg;
this.data = data;
}
public ResultBean(int code, String devMsg, String msg) {
this.code = code;
this.devMsg = devMsg;
this.msg = msg;
this.data = "";
}
public String getResult() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("code",code);
jsonObject.put("devMsg",devMsg);
jsonObject.put("msg",msg);
jsonObject.put("data",data);
return jsonObject.toString();
}
}
配置沒有找到Controller時丟擲異常,理論上這個是非必須的,有待考證。
spring:
mvc:
throw-exception-if-no-handler-found: true