Skip to content
Advertisement

Laravel create custom exception with parameters & return as JSON

I want to throw a custom exception if the variable is null and return it as JSON. I’ve tried like this:

Controller

JavaScript

Custom Exception

JavaScript

But when I am trying to test it using postman, the return I got is not the same as I wrote in NullException. It becomes like this: Postman response

Advertisement

Answer

In your case you are returning the exception as a response instead of throwing it. That’s why it’s displayed like this.

You could just have to throw the exception without the try/catch:

JavaScript

The laravel error handler will catch the exception & render it.

EDIT: Or as @miken32 pointed out you could re throw the exception to handle other exceptions:

JavaScript

enter image description here

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement