无法从异常控制器获取我的自定义异常消息

时间:2019-04-10 19:08:23

标签: rest spring-boot exception

为什么我收到“无法找到ID为4的com.example.Api_Angular.Dao.Person”而不是“此ID不存在的人”的信息。

 @GetMapping("/persons/{id}")
    public Person getPerson(@PathVariable int id)
    {
        Person person = personService.getPersonById(id);
        System.out.println(person);
        if(!(person instanceof Person))
        {
            throw new NoPersonException("Person with this id does not exist");
        }
        return person;
        }

即时消息:

{
"status": 400,
"msg": "Unable to find com.example.Api_Angular.Dao.Person with id 4",
"request": "uri=/myApp/persons/4"
}

应该是什么:

{
"status": 400,
"msg": "Person with this id does not exist",
"request": "uri=/myApp/persons/4"
}

我的自定义例外:

public class NoPersonException extends RuntimeException {
    String msg;

    public String getMsg() {
        return msg;
    }

    public NoPersonException() {
    }

    public NoPersonException(String message) {
        this.msg = message;
    }
}

错误响应:

@Data
@AllArgsConstructor
public class ErrorDetails {

    private int status;
    private String msg;
    private String request;

    public ErrorDetails() {
    }
}

异常控制器:

@RestControllerAdvice
public class CustomizedResponseEntityExceptionHandler{


    @ExceptionHandler
    public ResponseEntity<ErrorDetails> response(NoPersonException e,WebRequest webRequest)
    {
        ErrorDetails customerErrorResponse=new ErrorDetails(HttpStatus.NOT_FOUND.value(),e.getMessage(),webRequest.getDescription(false));

        return new ResponseEntity<>(customerErrorResponse,HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler
    public ResponseEntity<ErrorDetails> generalresponse(Exception e,WebRequest webRequest)
    {
        ErrorDetails customerErrorResponse=new ErrorDetails(HttpStatus.BAD_REQUEST.value(),e.getMessage(),webRequest.getDescription(false));

        return new ResponseEntity<>(customerErrorResponse,HttpStatus.BAD_REQUEST);
    }

被称为异常类型的问题吗? 您有什么解决方案如何解决这个问题? 我正在使用Spring Boot 2.2。

1 个答案:

答案 0 :(得分:0)

当您致电EntityNotFoundException时,肯定会收到personService.getPersonById(id)。您应该尝试将其包装在try/catch块中以了解更多信息。