如何从它的消息中分离异常类型

问题描述 投票:0回答:1

在spring boot应用程序中,我使用@ControllerAdvice处理异常。我能够处理异常。我的JSON消息是状态,错误,异常和路径。当我打印异常字符串时,我得到异常并且它也是消息。

我的定义是在异常参数中如何在没有消息的情况下仅打印异常类型。因为消息我打印错误?

还有一个Quation是我只使用一个类即Exception类处理所有类型的异常。对于每个例外,我在status code作为500。我们可以为不同类型的异常设置不同的状态代码吗?

我们可以在这里传递状态代码throw new NullPointerException("Null values are not allowed");

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ExceptionMessage> handleAllExceptionMethod(Exception ex,WebRequest requset,HttpServletResponse res) {   

        ExceptionMessage exceptionMessageObj = new ExceptionMessage();

        exceptionMessageObj.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        exceptionMessageObj.setError(ex.getLocalizedMessage());     
        exceptionMessageObj.setException(ex.toString());
        exceptionMessageObj.setPath(((ServletWebRequest) requset).getRequest().getServletPath());

        return new ResponseEntity<ExceptionMessage>(exceptionMessageObj, new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);

}

enter image description here

java spring-boot exception
1个回答
1
投票

您需要在邮件上设置名称,如下所示:

exceptionMessageObj.setException(ex.getClass().getCanonicalName());

例如:

System.out.println(new NoClassDefFoundError().getClass().getCanonicalName());

将返回

java.lang.NoClassDefFoundError
© www.soinside.com 2019 - 2024. All rights reserved.