温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring Boot如何处理异常和日志

发布时间:2025-02-18 10:28:55 阅读:97 作者:小樊 栏目:软件技术
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Spring Boot中,处理异常和记录日志是两个非常重要的方面。下面分别介绍如何处理异常和记录日志。

处理异常

  1. 全局异常处理: 使用@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);
        }
    }
    
  2. 自定义异常: 创建自定义异常类,继承RuntimeException或其他合适的异常类。

    public class CustomException extends RuntimeException {
        public CustomException(String message) {
            super(message);
        }
    }
    
  3. 在控制器中抛出自定义异常: 在控制器方法中根据需要抛出自定义异常。

    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";
        }
    }
    

记录日志

  1. 配置日志: Spring Boot默认使用Logback作为日志框架。可以在application.propertiesapplication.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
    
  2. 使用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";
        }
    }
    
  3. 使用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元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×