wimdeblauwe / error-handling-spring-boot-starter

Spring Boot starter for configurable REST API error handling
https://wimdeblauwe.github.io/error-handling-spring-boot-starter/
Apache License 2.0
423 stars 51 forks source link

Server-Sent Event Support #89

Open Caceresenzo opened 5 months ago

Caceresenzo commented 5 months ago

I was messing around with server-sent events and managed to make it works with your library.

Server-sent events works by using a SseEmitter and we can "return" an exception using SseEmitter.completeWithError(Throwable). However the ApiErrorResponse class does not support being converted to text/event-stream content-type.

Here is my experiment: https://github.com/Caceresenzo/random/blob/master/test/spring/server-sent-event/src/main/java/com/example/demo/converter/ApiErrorResponseToTextEventStreamMessageConverter.java

And the dummy project itself: https://github.com/Caceresenzo/random/tree/master/test/spring/server-sent-event Start the project and go on: http://localhost:8080/hello

It should give you:

data:{"status":"starting","progress":0}

[ ... ]

event:error:400
data:{"code":"SOMETHING_HAPPEN","message":null,"why":"bad xyz on abc"}

I made the event name error:<status code> but I think this should be configurable?

I can try to make a pull request, just let me know what you think.

wimdeblauwe commented 5 months ago

Interesting idea. If I look at what Chrome shows in the developer tools, I wonder if it is a good idea to have error:400 as the type:

CleanShot 2024-04-24 at 14 52 45@2x

Do you have an idea how you would make it configurable ?

Caceresenzo commented 5 months ago

The spec don't seem to have anything regarding event names.

And since the response header has already been committed, there is no way of "changing" the status of the response.

This error:{status} was more like to differentiate between client errors (4XX) and server errors (5XX). But that means that the client will have to handle it; if event.name starts with "error:" then ...

To be honest, this was just an experiment since completeWithError would double-fails as it was unable to render the ApiErrorResponse to the stream.