在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作為日志框架??梢栽?code>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應用中有效地處理異常和記錄日志。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。