Return a 404 when a resource is not found in Spring Boot I wrote this code in order to return a http status of not found to my users in case the resource is not present in the DB.

@RestController
public class ExampleController {

    public final ExampleService exampleService;

    @Autowired
    public ExampleController(ExampleService exampleService) {
        this.exampleService = exampleService;
    }

    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public class ResourceNotFoundException extends RuntimeException {
    }

    @GetMapping("/api/mappings/get-by-id/{id}")
    public ExampleDto getExampleById(@PathVariable String id) {
        Example example = exampleService.findById(id).orElse(null   );
        if (example == null) throw new ResourceNotFoundException();
        return new ExampleDto(example);
    }

}


I would like to know if this code can be considered good and robust enough or if it can be improved and how.
Your URL path isn't very RESTlike. You have built the URL to describe an operation when a more common approach is to build the URL to describe a resource.

So instead of https://example.com/api/mappings/get-by-id/42 one would build a URL like https://example.com/api/mappings/42.

The name get-by-id is fully redundant in REST world as the "get" operation is already defined in the HTTP GET-method (the @GetMapping annotation in Spring Boot) and identifying resources by their identifier is always the default operation :).