使用原理
代码实现
定义在一个共有的包中
package com.heima.common.excption;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
@Log4j2
public class ExceptionCatch {
@ExceptionHandler(Exception.class)
public ResponseResult exception(Exception e){
e.printStackTrace();//打印异常
log.error("exception:catch{}",e.getMessage());//异常日志
return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
}
}
集成到项目中使用
在处理异常的模块中新增类ExceptionCatchConfig
package com.heima.admin.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.heima.common.excption")//ExceptionCatch扫描所在包
public class MyExceptionConfig {
}