Laravel is one of the most used backend frameworks in building modern APIs for applications. When building APIs or writing codes (either simple or complex algorithms), no developer can escape from encountering errors. In this short article, I'll be sharing a simple tips on how to handle these errors.
These are some of the reasons why you need to learn error handling:
- To avoid unnecessary termination of your program.
- To avoid security threat on your application.
- Proper communication to the end user or the API tester of your application. etc
Here are common errors you will likely encounter when building your APIs:
- MethodNotAllowedHttpException
- NotFoundHttpException
- BadMethodCallException
In Laravel, all exceptions are properly handled in the:
\app\Exceptions\Handler.php.
After Locating the path, you will find the render method, inside the method, all exceptions should be written there.
1.MethodNotAllowedHttpException usually occurs when you're trying to POST to a GET route or you're trying to GET from a POST route or similar
Solution:
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
public function render($request, Throwable $exception){
if ($exception instanceof MethodNotAllowedHttpException)
{
return response()->json( [
'success' => 0,
'message' => 'This Method is not allowed for the
requested route',
'status' => '405',
], 405 );
}
}
2.NotFoundHttpException in Laravel always means that it was not able to find a router for a particular URL
Solution:
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
public function render($request, Throwable $exception)
if ($exception instanceof NotFoundHttpException) {
return response()->json( [
'success' => 0,
'message' => 'This Route is not found',
'status' => '404',
], 404 );
}
}
3.BadMethodCallException is thrown if a callback refers to an undefined method or if some arguments are missing.
Solution:
public function render($request, Throwable $exception){
if ($exception instanceof \BadMethodCallException) {
return response()->json( [
'success' => 0,
'message' => 'Bad Method Called',
'status' => '404',
], 404 );
}
}
NOTE: There should not be multiple render methods. Just one! You put all your exceptions inside one render method
I hope this short article has been helpful to you? Kindly add more exceptions if you know of any other ones.
Top comments (0)