1. 程式人生 > 實用技巧 >全域性異常響應資訊處理

全域性異常響應資訊處理

import com.dkjk.vo.ResponseBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.servlet.http.HttpServletRequest; @RestControllerAdvice @Slf4j public class GlobalExceptionHandler { // 捕捉其他所有異常 @ExceptionHandler(value = Exception.class
) public ResponseBean apiErrorHandlerException(HttpServletRequest request, Exception e) { String requestMethod = request.getMethod(); String requestURI = request.getRequestURI(); log.error("用" + requestMethod + "方式請求" + requestURI + "時出現異常", e); String eMessage = e.getMessage();
if (e instanceof HttpRequestMethodNotSupportedException) { log.warn("請求方式錯誤,{}", e.getMessage()); return new ResponseBean(400, "請求方式錯誤", eMessage); } if (e instanceof MissingServletRequestParameterException) { log.warn("引數錯誤,缺少引數,{}", e.getMessage()); return new ResponseBean(400, "請求引數錯誤", e.getMessage()); } if (e instanceof MethodArgumentNotValidException) { log.warn("引數錯誤,引數校驗不通過導致的,{}", e.getMessage()); MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) e; String defaultMessage = methodArgumentNotValidException.getBindingResult().getFieldError().getDefaultMessage(); return new ResponseBean(400, "請求引數錯誤", defaultMessage); } if (e instanceof HttpMessageNotReadableException) { log.warn("引數錯誤,請求引數進行反序列化時導致的(引數型別不對應什麼的),{}", e.getMessage()); return new ResponseBean(400, "請求引數錯誤", e.getMessage()); } return new ResponseBean(99999, "系統出現異常", null); } }