原文地址
@ControllerAdvice和@ExceptionHandler
通常组合使用,用于处理全局异常,示例代码如下:
@ControllerAdvice
@Configuration
@Slf4j
public class GlobalExceptionConfig {private static final Integer GLOBAL_ERROR_CODE = 500;@ExceptionHandler(value = Exception.class)@ResponseBodypublic void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception e) throws Exception {log.error("【统一异常处理器】", e);ResultMsg<Object> resultMsg = new ResultMsg<>();resultMsg.setCode(GLOBAL_ERROR_CODE);if (e instanceof CommonException) {CommonException ex = (CommonException) e;if(ex.getErrCode() != 0) {resultMsg.setCode(ex.getErrCode());}resultMsg.setMsg(ex.getErrMsg());}else {resultMsg.setMsg(CommonErrorMsg.SYSTEM_ERROR.getMessage());}WebUtil.buildPrintWriter(response, resultMsg);}}
@ActiveProfiles
一般作用于测试类上, 用于声明生效的 Spring 配置文件,比如指定application-dev.properties配置文件。
@RunWith和@SpringBootTest
一般作用于测试类上, 用于单元测试用,示例如下:
@ActiveProfiles("dev")
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestJunit {@Testpublic void executeTask() {//测试...}
}