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.
@Autowired
on constructor injection. Cheers just saved 2 line of code in each Component \$\endgroup\$