全局异常需要添加@ControllerAdvice@Component这两个注解
如果将全局异常放到公共的maven项目模块中依赖不可传递
公共的全局异常相当于以jar包的形式加入到需要用到的其他工程中
所以在其他模块中需要使用这个全局异常需要配置包扫描,
@SpringBootApplication(scanBasePackages = "com.qf",exclude = DataSourceAutoConfiguration.class)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<optional>true</optional>
</dependency>
@ControllerAdvice
@Component
public class ExceptionHanlder {
//业务异常(程序员手动抛出的异常)
@ExceptionHandler(ShopException.class)
@ResponseBody
public ResultEntity businessException(ShopException e){
System.out.println("出现了业务异常");
return ResultEntity.error(e.getMsg());
}
//系统异常(程序员写的bug)
@ExceptionHandler(Exception.class)
@ResponseBody
public ResultEntity systemException(Exception e){
System.out.println("系统出现异常了");
return ResultEntity.error("系统正在维护");
}
}