在Spring Boot中,处理异常和记录日志是两个非常重要的方面。下面分别介绍如何处理异常和记录日志。
全局异常处理:
使用@ControllerAdvice
和@ExceptionHandler
注解来创建全局异常处理器。
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleException(Exception e) {
return new ResponseEntity<>("An error occurred: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(CustomException.class)
public ResponseEntity<String> handleCustomException(CustomException e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
自定义异常:
创建自定义异常类,继承RuntimeException
或其他合适的异常类。
public class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
在控制器中抛出自定义异常: 在控制器方法中根据需要抛出自定义异常。
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class MyController {
@GetMapping("/test")
public String test() {
if (someCondition) {
throw new CustomException("This is a custom exception.");
}
return "Test successful";
}
}
配置日志:
Spring Boot默认使用Logback作为日志框架。可以在application.properties
或application.yml
中配置日志级别和输出格式。
# application.properties
logging.level.root=INFO
logging.level.com.example=DEBUG
logging.file.name=app.log
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss} - %msg%n
使用SLF4J和Logback: 在代码中使用SLF4J和Logback记录日志。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class MyController {
private static final Logger logger = LoggerFactory.getLogger(MyController.class);
@GetMapping("/test")
public String test() {
logger.info("Test method called");
if (someCondition) {
logger.error("An error occurred in test method");
throw new CustomException("This is a custom exception.");
}
return "Test successful";
}
}
使用AOP记录日志: 使用Spring AOP来记录方法的进入和退出。
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggingAspect {
private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);
@Before("execution(* com.example..*.*(..))")
public void logBefore(JoinPoint joinPoint) {
logger.info("Entering method: " + joinPoint.getSignature().getName());
}
@AfterReturning(pointcut = "execution(* com.example..*.*(..))", returning = "result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
logger.info("Exiting method: " + joinPoint.getSignature().getName() + " with result: " + result);
}
}
通过以上方法,可以在Spring Boot应用中有效地处理异常和记录日志。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。