Spring boot Spring启动异常详细信息

Spring boot Spring启动异常详细信息,spring-boot,exception-handling,Spring Boot,Exception Handling,我正在尝试将异常记录在基于spring boot的web服务中 所以我使用了GlobalExceptionHandler 我的代码: @ControllerAdvice @RestController public class GlobalExceptionHandler { @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(value = Exception.class)

我正在尝试将异常记录在基于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();
    }
 }
代码运行良好。我想要的是异常详细信息。我是说发生异常的代码?文件名/行?还是我必须解析stacktrace?我的意思是,spring boot一定为此想了些什么?

使用IDE

如果您正在使用任何IDE,请转到控制台窗口

透明控制台 重复导致异常的操作 在控制台CTRL+F中搜索错误 查找上面的行如果没有找到包含错误的行的正上方,请查找2-3行。此行包含发生异常的类、方法的详细信息。 不看控制台或日志

如果您想在生产中使用它,那么至少要处理已知的异常,如BAD_请求、NOT_FOUND等。下面的方法可能有助于向异常类添加额外参数:

这里是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();
    }
 }

这是已知的常见异常。我们需要向您抛出的所有自定义异常添加额外的参数ClassName,这可能需要很少的额外代码,但我认为这就是方法。希望现在能有所帮助

afaikspring没有任何东西来解析异常,以便找到异常发生的行。最好的方法是迭代堆栈跟踪,检查包名,并获取您感兴趣的包名,行信息也将包含在其中,以便您可以随心所欲地形成消息。您应该使用一些日志框架来捕获错误日志,而不是sysout语句。就跟踪而言,您必须使用stacktrace手动执行。我需要在生产中使用此功能,哦..您没有提到..然后您必须在控制器端检查是否存在任何异常。。至少有已知的例外情况。。否则,将选择解析堆栈跟踪..@Ankit my bad for error answer
@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();
    }
 }