@RestControllerAdvice
public class RestExceptionHandler {
@ExceptionHandler(value = { BusinessException.class })
public Result business(BusinessException ex) {
return Result.fail("业务异常:"+ex.getMessage());
}
@ExceptionHandler(value = { MethodArgumentNotValidException.class })
public Result methodArgumentNotValidException(MethodArgumentNotValidException ex) {
String field=ex.getBindingResult().getFieldError().getField().replace("parameter.","");
String message=ex.getBindingResult().getFieldError().getDefaultMessage();
return Result.fail("验证失败:字段["+field+"]"+message);
}
@ExceptionHandler(value = { Exception.class })
public Result exception(Exception ex) {
return Result.fail("系统异常:"+ex.getMessage());
}
}
但是,某些情况下,我们的全局handler无效了。咋个回事儿呢?
①spring boot Java配置检查@SpringBootApplication(scanBasePackages = )(scanBasePackages 配置的包是否包含这个类默认情况下spring boot项目扫描的是@SpringBootApplication注解所在类的包及子包)
② xml配置的spring 普通项目检查<context:component-scan base-package="com.test"/>
https://www.leftso.com/article/430.html