【问题标题】:Spring Boot Exception detailsSpring Boot 异常详细信息
【发布时间】:2017-07-27 09:14:52
【问题描述】:

我正在尝试在基于 Spring Boot 的 Web 服务中记录异常。

所以我使用了 GlobalExceptionHandler 我的代码:

@ControllerAdvice  
@RestController  
public class GlobalExceptionHandler {  

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)  
    @ExceptionHandler(value = Exception.class)
    public String handleException(Exception e){

        System.out.println("Ankit == "+e.getMessage());
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        System.out.println(errors.toString());
        return e.getMessage();
    }
 }

代码运行良好。我想要的是异常细节。我的意思是发生异常的代码?文件名/行?还是我必须解析堆栈跟踪?我的意思是 spring boot 一定是为此想到了什么?

【问题讨论】:

  • Afaik spring 没有任何东西可以解析异常以找到发生异常的行。最好的办法是遍历堆栈跟踪,检查包名称并获取您感兴趣的包名称(线路信息也将包含在其中,以便您可以随意形成消息)。
  • 您应该使用一些日志框架来捕获错误日志,而不是 sysout 语句。就跟踪而言,您必须使用 stacktrace 手动进行。

标签: spring-boot exception-handling


【解决方案1】:

使用 IDE

如果您使用任何 IDE,请转到 Console Window

  1. 清除控制台
  2. 导致异常的重复操作
  3. Console (CTRL + F) 中搜索ERROR
  4. 查找上面的行(如果在上面没有找到,请查找 2-3 行)包含ERROR 的行。此行包含发生异常的类、方法的详细信息。

无需查看控制台或日志

如果您想在生产中使用它,那么按照下面的方式处理至少已知的异常(如 BAD_REQUEST、NOT_FOUND 等)可能会有所帮助(向异常类添加额外的参数)

Employee employee = employeeService.getEmployeeById(employeeId);
if (null == employee) {
logger.error("No tenant exists for employeeId:"+employeeId);
throw new ObjectNotFoundException("Emplyee Not Found",  this.getClass().getSimpleName();));
}

这里this.getClass().getSimpleName(); 将作为EmployeeController 类的参数传递。所以在ObjectNotFoundException中我们可以添加一个参数ClassName,当你在GlobalExceptionHandler中处理它时,你可以像下面那样做,

@ControllerAdvice  
@RestController  
public class GlobalExceptionHandler {  
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)  
    @ExceptionHandler(value = Exception.class)
    public String handleException(Exception e){

        System.out.println("Ankit == "+e.getMessage());
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        String classWithExceptionName = e.getClassName(); 
        // you need to add this above getter method to your Exception Class
        System.out.println(errors.toString());
        return e.getMessage();
    }
 }

这是针对已知的常见异常。我们需要将extra parameter(ClassName) 添加到您抛出的所有自定义异常中,这可能是一些额外的代码,但我认为这就是方法。希望它现在有所帮助。

【讨论】:

  • 我需要在生产环境中使用它,
  • 哦..你没有提到..那么你将不得不在控制器端检查任何异常..至少已知异常..否则解析堆栈跟踪将是选项。 .@Ankit 我错了答案
猜你喜欢
  • 2011-03-20
  • 1970-01-01
  • 2013-10-08
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多