Cleaning up a genserverprocess before it exits

I have a genserver that makes call it 3rd party api and i am doing a pattern matching on the response. Sometimes the pattern doesnt match and the process crashes. How do I clean up some state like update a database table to change the state of the task to failed ? are there some callbacks?

You can just add more pattern-matching variants to your handle_info or handle_call function and do those failure mode actions there.

The easiest is as @dimitarvp mentioned, however I would recommend using this only when the amount of code is small.

Ideally I would recommend to have a custom task supervisor and this way you can catch all the exit signals and do the cleanup either in a separate process or in the supervisor itself.

There is also the option of monitoring the process, supervisors are using this functionality under the hood, this is a lower level functionality that should be avoided in favor of other abstractions.

1 Like

If he has any sort of error-tracking system a la Rollbar / Sentry / AppSignal etc. then he’ll get the errors anyway, which he can then use to enrich his GenServer callbacks so it doesn’t crash but react to the unhappy path.

But you’re right that this can get unwieldy as the code size grows. Still, I am not sure it happens often.

1 Like

I suppose it depends on whether you need to handle each error case separately or just have an error catch-all which cleans up and then dies.

3 Likes