package com.hyperdai.base;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* 根據Accept頭的內容,輸出不同格式的錯誤響應。
* 比如針對瀏覽器的請求生成html頁面,針對其它請求生成json格式的返回。字段爲accept的text/html的內容來判斷
*
* @author daizhijia
* @create 2020-05-01 3:52 上午
*/
@Controller
public class AppErrorController implements ErrorController {
private static final String ERROR_PATH = "/error";
private ErrorAttributes errorAttributes;
@Override
public String getErrorPath() {
return ERROR_PATH;
}
@Autowired
public AppErrorController(ErrorAttributes errorAttributes) {
this.errorAttributes = errorAttributes;
}
/**
* Web頁面錯誤處理
*/
@RequestMapping(value = ERROR_PATH, produces = "text/html")
public String errorPageHandler(HttpServletRequest request, HttpServletResponse response) {
int status = response.getStatus();
switch (status) {
case 403:
return "403";
case 404:
return "404";
case 500:
return "500";
}
return "index";
}
/**
* 除Web頁面外的錯誤處理,比如Json/XML等
*/
@RequestMapping(value = ERROR_PATH)
@ResponseBody
public ApiResponse errorApiHandler(HttpServletRequest request) {
RequestAttributes requestAttributes = new ServletRequestAttributes(request);
Map<String, Object> attr = this.errorAttributes.getErrorAttributes(requestAttributes, false);
int status = getStatus(request);
return ApiResponse.ofMessage(status, String.valueOf(attr.getOrDefault("message", "error")));
}
private int getStatus(HttpServletRequest request) {
Integer status = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (status != null) {
return status;
}
return 500;
}
}
Springboot異常處理AppErrorController
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.