V
V
vitya_brodov2022-03-25 12:46:47
Java
vitya_brodov, 2022-03-25 12:46:47

How to pass an exception to the response body?

I have a simple CRUD-API where you can get user data by id.
Question: How can I pass an exception to the response body if the user is not found by id?

my code:

@GetMapping("/user")
    public ResponseEntity getUserById(@RequestParam(value = "id") Long id) {
        UserEntity entity = service.getUserById(id);
        if (entity != null) {
            return new ResponseEntity(entity, HttpStatus.FOUND);
        } else
            return ResponseEntity.ok(new NotFoundException("Given user id  not found", "Insert data at first"));
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2022-03-25
@vitya_brodov

@GetMapping("/user")
    public ResponseEntity getUserById(@RequestParam(value = "id") Long id) {
        UserEntity entity = service.getUserById(id);
        if (entity != null) {
            return new ResponseEntity(entity, HttpStatus.FOUND);
        }

        throw new ResponseStatusException(
              HttpStatus.NOT_FOUND, 
              "Given user id  not found", 
              new NotFoundException("Insert data at first")
         );
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question