Does anyone know how I can let my Spring controlle...
# spring
k
Does anyone know how I can let my Spring controller return a 404? I thought I could just return a nullable variable and if it is null Spring would translate it to a 404. Do I really need to use
ResponseEntity
specifically?
n
how does spring knows what
null
means? it could mean a 500 or anything... you’ve to set the http response code specifically
k
Okay, I thought there would be a shortcut because in Java with the @RestController a GetMapping that calls the repo and returns nothing aka null it returns a 404
n
d
i was just about to say that
i've seen most projects do it with NotFoundException
which imo is fugly
also a lot of projects do this for a gazillion of other errors with a global exception handler
f
you can annotate with
Copy code
@ResponseStatus(HttpStatus.NOT_FOUND)
or you can
Copy code
return ResponseEntity.notFound()
i
I'd recommend writing a @ControllerAdvice to handle exceptions in a uniform way (example https://github.com/istonikula/realworld-api/blob/master/realworld-app/web/src/main/kotlin/io/realworld/ErrorHandler.kt), keeping your domain independent of the framework used and communicate domain errors with explicit types (example https://github.com/istonikula/realworld-api/blob/master/realworld-domain/src/main/kotlin/io/realworld/domain/core/Users.kt), then convert and forward the domain errors as exceptions in the adapter (in this case the rest api controller https://github.com/istonikula/realworld-api/blob/master/realworld-app/web/src/main/kotlin/io/realworld/Users.kt), so both the unexpected and expected cases will be serialized in the same place