目前我们的服务大多数通过springboot开发的服务端。针对接口返回类型,可以分为json和html两种返回结果。
针对两种返回结果,实现了500 400 通用错误处理逻辑。
```
package com.xxxx.health.insurance.web;
import com.xxxx.health.insurance.exception.BusinessException;
import com.xxxx.health.insurance.exception.ProtocolErrorCode;
import com.xxxx.health.insurance.proto.ProtocolResponse;
import com.xxxx.health.insurance.utils.LoggerUtils;
import org.slf4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ControllerAdvice
@RestController
public class GlobalExceptionAdvice {
private static final Logger logger = LoggerUtils.getLogger(GlobalExceptionAdvice.class);
public static final String PAGE_404 = "error/404";
public static final String PAGE_500 = "error/500";
//页面请求标记
public static final String PAGE_TAG = ".html";
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public Object requestHandlingNoHandlerFound(HttpServletRequest request, Exception exception) {
if (isPageAccess(request)){
return new ModelAndView(PAGE_404);
}
ProtocolResponse resp = new ProtocolResponse();
resp.setProtocolError(ProtocolErrorCode.REQUEST_URL_NOT_FUND);
resp.initTimestamp();
logger.error(resp.getMsg(), exception);
return resp;
}
@ExceptionHandler(MissingServletRequestParameterException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public Object missingParameterHandler(HttpServletRequest request, Exception exception) {
if (isPageAccess(request)){
return new ModelAndView(PAGE_404);
}
ProtocolResponse resp = new ProtocolResponse();
resp.setProtocolError(ProtocolErrorCode.REQUEST_PARAMS_INVALID);
resp.initTimestamp();
logger.error(exception.getMessage(), exception);
return resp;
}
@ExceptionHandler(Exception.class)
public Object exceptionHandler(Exception e,HttpServletRequest request, HttpServletResponse response) {
if (isPageAccess(request)){
return new ModelAndView(PAGE_500);
}
ProtocolResponse resp = new ProtocolResponse();
if (e instanceof BusinessException) {
resp.setCode(((BusinessException) e).getCode());
resp.setMsg(((BusinessException) e).getMsg());
resp.setResult(((BusinessException) e).getResult());
} else {
resp.setCode(ProtocolErrorCode.SYSTEM_UNKNOWN_ERROR.getCode());
resp.setMsg(ProtocolErrorCode.SYSTEM_UNKNOWN_ERROR.getMessage());
}
resp.initTimestamp();
logger.error(resp.getMsg(), e);
return resp;
}
private boolean isPageAccess(HttpServletRequest request) {
String requestURI = request.getRequestURI();
return requestURI.endsWith(PAGE_TAG);
}
}
```