Web Programming TutorialsLearn How To Deal With API Error Handling With Custom Error Classes

Learn How To Deal With API Error Handling With Custom Error Classes

It becomes important to handle errors in the API development. Since the API usually serves as an interface to many clients, it is important to provide descriptive pop up error message when something goes wrong. Moreover, Laravel provides great support for error and exception handling.

What we’ll be building?

We’ll be building a simple REST API that handles Create, Read, Update and Delete tasks for a Quote resource. Also, we want our API to throw a custom error whenever you try to obtain a resource that doesn’t exist in our database. Let’s take a look at some of our endpoints.

  • GET /quotes – Fetch all the quote resource
  • POST /quote – Create a new quote resource
  • GET /quote/{id} – Fetch a quote resource by id
  • PUT /quote/{id} – Update a quote resource by id
  • DELETE /quote/{id} – Delete a quote resource by id

For this tutorial, I’ll assume you’ve set up Laravel already.

Getting Started

Let’s set up our Model, Controller, and Migration. Thankfully, Laravel can handle all of this with a single command. Using the following command artisan run:

php artisan make:model Quote -m -c

Tip: – The `-m` and `-c` flags will create a migration and controller file associated with the model for you.
Our Quote resource will have a single attribute which will be the content. In the database/migrations directory, edit the quote migration to reflect the database structure with the following code.

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateQuotesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('quotes', function (Blueprint $table) {
            $table->increments('id');
            $table->string('content');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('quotes');
    }
}

Edit .env file with your database configurations and then run the following command to execute the migration.

php artisan migrate

Creating Custom Error Classes

Let’s create our custom error class that will throw an error, whenever we try to obtain an invalid resource. In the app/Exceptions directory, create a ResourceNotFoundException.php file and edit with the following code:

<?php

namespace App\Exceptions;

use Exception;

class ResourceNotFoundException extends Exception
{
    public function render()
    {
        return response()->json(['message'=>'Quote not found'], 404);
    }
}

We will define a render method here and return a JSON response saying that, the quote could not be found, followed by 404 error.
Tip: The render method converts a given exception into an HTTP response that should be sent back to the browser.

Controller Methods

Navigate to the app/Http/Controller directory and edit the QuoteController created earlier with the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Quote;
use App\Exceptions\ResourceNotFoundException;

class QuoteController extends Controller
{
    public function getAllQuotes()
    {
      $quotes = Quote::all();

      return response()->json(['data'=>$quotes, 'status_code'=>200]);
    }

    public function getQuote($id)
    {
      $quote = Quote::find($id);

       if(!$quote){
        throw new ResourceNotFoundException;
      }

      return response()->json(['data'=>$quote]);
    }

    public function createQuote(Request $request)
    {
     
      $quote = new Quote;

      $quote->content= $request->content;
      $quote->save();

      return response()->json(['data'=>$quote, 'status_code'=>201]);
    }
    
       public function updateQuote(Request $request, $id)
    {
     
      $quote = Quote::find($id);

       if(!$quote){
        throw new ResourceNotFoundException;
      }

      $quote->content= $request->content;
      $quote->save();

      return response()->json(['data'=>$quote, 'message'=> 'quote updated successfully', 'status_code'=>200]);
    }

       public function deleteQuote(Request $request, $id)
    {
     
      $quote = Quote::find($id)->delete();

      if(!$quote){
        throw new ResourceNotFoundException;
      }

      return response()->json(['message'=>'Quote deleted successfully', 'status_code'=>200]);
    }
}

At the top of the QuoteController, we imported the Quote model and the ResourceNotFoundException class which is the custom error handler,created earlier.

  • getAllQuotes() – return all the quotes as a JSON response.
  • getQuote() – fetches a single quote resource by its id. Here, we will check whether the quote is invalid. If it’s an invalid quote, we can give the input message as ResourceNotFoundException Error.
  • createQuote() – creates a new quote and return to the newly created quote as a JSON response.
  • updateQuote() – updates a quote resource by its id and throws our custom error if it’s an invalid quote.
  • deleteQuote() – deletes a quote resource by its id.

Routes

Let’s add our routes. Since we’re working with APIs, open up the api.php file in the routes folder and add the following code:

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::get('/quotes', 'QuoteController@getAllQuotes');
Route::get('/quote/{id}', 'QuoteController@getQuote');
Route::post('/quote', 'QuoteController@createQuote');
Route::put('/quote/{id}', 'QuoteController@updateQuote');
Route::delete('/quote/{id}', 'QuoteController@deleteQuote');

Testing our Endpoints

We’ll be making use of POSTMAN to test the endpoints.
Creating a Quote
Fetching an invalid quote
You can see when we try fetching a quote that doesn’t exist in our database, our custom error is thrown.

Conclusion: –
While working with APIs in Laravel, error classes are a great way of reporting and handling errors.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -