业务系统抛出异常,会被该类捕获
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 全局异常捕捉处理
*
* @author liyk
* @date 2018/10/11
*/
@ControllerAdvice
public class GlobalControllerAdvice {
private static final Logger LOGGER = LoggerFactory.getLogger(GlobalControllerAdvice.class);
@ResponseBody
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public Result errorHandler(MethodArgumentNotValidException ex, HttpServletRequest request, HttpServletResponse response) {
// proccess(request, response);
BindingResult result = ex.getBindingResult();
if (result.hasErrors()) {
for (FieldError fieldError : result.getFieldErrors()) {
this.LOGGER.error(fieldError.getDefaultMessage());
return Result.illegalArguments();
}
}
return Result.fail();
}
@ResponseBody
@ExceptionHandler(value = GenericException.class)
public Result errorHandler(GenericException ex, HttpServletRequest request, HttpServletResponse response) {
// proccess(request, response);
this.LOGGER.error("异常:业务异常:", ex);
return Result.custom(ex.getCode(), ex.getMsg());
}
/**
* 全局异常后跨域解决
* @param request
* @param response
*/
private void proccess(HttpServletRequest request, HttpServletResponse response) {
String originHeader = request.getHeader("Origin");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-type", "application/json;charset=UTF-8");
response.setStatus(200);
response.setHeader("Access-Control-Expose-Headers", "verifyCode");
response.setHeader("Access-Control-Allow-Origin", originHeader);
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
}
}