Why the result of ModelNotFoundException is HttpNotFoundException
Hello guys,
I'm kinda newbie in Laravel Error handling.
I'm playing around with API, and I needed to customize the response of ModelNotFoundException.
I followed the documentation, using $this->renderable. But every time I throw an model not found exception, the result is always HttpNotFoundException. I looked into the source and I found this
Because you are making an HTTP request and the resource was not found. No need to give away too much information about what is the exact error since it doesn't matter to the end-user.
Documentation is open source so if you notice something is missing you can add it.
I needed to customize the response of ModelNotFoundException.
@koossay You don’t. If a user’s making a request for a resource and that resource (model) doesn’t exist, then a 404 Not Found is the appropriate response.
I guess I didn't explain too much, my bad.
What I meant is what if I'm building an API, the ModelNotFoundException is rendered to the appropriate view, but I need a JSON response.
I can do that in the controller with return response()->json();
But I want things to work smoothly. However I managed it to work only in the API.
Also Thank you @bugsysha, you made things clear, not too much information is generally a good thing.
What I meant is what if I'm building an API, the ModelNotFoundException is rendered to the appropriate view, but I need a JSON response
@koossay You’ll get a JSON response if you tell the server you want a JSON response. If you send your requests with a Accept: application/json header, then the server will send you back a JSON response.
I can do that in the controller with return response()->json(); But I want things to work smoothly.
As above. If you’re just hitting API URLs in the browser then it’s going to include a header of Accept: */*, which translates to, “Hey, server, I’ll accept anything”. So Laravel will, be default, return you a HTML view.
So if you want JSON, you need to specify in your request that’s what you’ll accept.
It’s probably worth getting familiar with common parts of HTTP if you’re going to build a HTTP-based API. So familiar with things like common request and response headers, status codes and their intended usages, etc.