全局异常处理器

132 阅读1分钟

从 Spring 3.0 - Spring 3.2 版本之间,对 Spring 架构和 SpringMVC 的Controller 的异常捕获提供了相应的异常处理。

  • @ExceptionHandler

    Spring3.0提供的标识在方法上或类上的注解,用来表明方法的处理异常类型。

  • @ControllerAdvice

    Spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强,在项目中来增强SpringMVC中的Controller。通常和 @ExceptionHandler 结合使用,来处理SpringMVC的异常信息。

  • @ResponseStatus

    Spring3.0提供的标识在方法上或类上的注解,用状态代码和应返回的原因标记方法或异常类。调用处理程序方法时,状态代码将应用于HTTP响应。

    通过上面的两个注解便可实现微服务端全局异常处理,具体代码如下:

@ControllerAdvice
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(HuaCaisException.class)  // HuaCaisException自定义异常类,继承RuntimeException
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse customException(HuaCaisException e) {
        log.error("【系统异常】{}", e.getErrMessage(), e);
        return new RestErrorResponse(e.getErrMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse exception(Exception e) {
        log.error("【系统异常】{}", e.getMessage(), e);
        //CommonError自定义的通用错误信息类
        return new RestErrorResponse(CommonError.UNKOWN_ERROR.getErrMessage());
    }
    
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse doValidException(MethodArgumentNotValidException argumentNotValidException) {

	BindingResult bindingResult = argumentNotValidException.getBindingResult();
	StringBuffer errMsg = new StringBuffer();

	List<FieldError> fieldErrors = bindingResult.getFieldErrors();
	fieldErrors.forEach(error -> {
		errMsg.append(error.getDefaultMessage()).append(",");
	});
	log.error(errMsg.toString());
	return new RestErrorResponse(errMsg.toString());
    }
}