A lightweight package for handling API error responses.

Overview

Laravel API Errors

Latest Version on Packagist Total Downloads GitHub Actions

This package provides an easy way to manage and handle error response for JSON API's.

Installation

You can install the package via composer:

composer require 3sidedcube/laravel-api-errors

Usage

There are 2 ways of generating an API error response:

API Error Exception

This package provides an exception called ApiErrorException which you can extend. There are 3 methods which can be set (2 of which are required):

  • code() - This is a short string indicating the error code (required).
  • message() - A human-readable message providing more details about the error (required).
  • statusCode() - This HTTP status code of the error response. By default, this is set to 400 and is optional.

Once you have an exception, you can use the fromException() method to generate an API error response:

use Cube\LaravelApiErrors\ApiErrorResponse;
use Cube\LaravelApiErrors\Exceptions\ApiErrorException;

class UserBannedException extends ApiErrorException
{
    /**
     * A short error code describing the error.
     *
     * @return string
     */
    public function code(): string
    {
        return 'user_account_banned';
    }

    /**
     * A human-readable message providing more details about the error.
     *
     * @return string
     */
    public function message(): string
    {
        return 'User account banned.';
    }

    /**
     * The api error status code.
     *
     * @return int
     */
    public function statusCode(): int
    {
        return 403;
    }
}

$exception = new UserBannedException();

// This will return an instance of JsonResponse
$response = ApiErrorResponse::fromException($exception);

Returning this response would generate the following json response:

{
    "error": {
        "code": "user_account_banned",
        "message": "User account banned."
    }
}

Automatically returning the exception response

If you want to automatically return the JSON response from the exception, you can add the exception to the $doNotReport array in your app/Exceptions/Handler.php like so:

use Cube\LaravelApiErrors\Exceptions\ApiErrorException;

protected $dontReport = [
    ApiErrorException::class,
];

Passing data directly

Alternatively you can use the create() method to create an API error response:

use Cube\LaravelApiErrors\ApiErrorResponse;

// This will return an instance of JsonResponse
$response = ApiErrorResponse::create('user_account_banned', 'User account banned.', 403);

Returning this response would generate the following json response:

{
    "error": {
        "code": "user_account_banned",
        "message": "User account banned."
    }
}

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Credits

License

Laravel Horizon is open-sourced software licensed under the MIT license.

You might also like...
Provides a powerful error response system for Laravel
Provides a powerful error response system for Laravel

Laravel Exceptions Laravel Exceptions was created by, and is maintained by Graham Campbell, and provides a powerful error response system for both dev

Jetstrap is a lightweight laravel 8 package that focuses on the VIEW side of Jetstream / Breeze package installed in your Laravel application

A Laravel 8 package to easily switch TailwindCSS resources generated by Laravel Jetstream and Breeze to Bootstrap 4.

Lightweight JSON:API resource for Laravel

JSON:API Resource for Laravel A lightweight Laravel implementation of JSON:API. This is a WIP project currently being built out via livestream on my Y

A lightweight domain event pattern implementation for Doctrine2.
A lightweight domain event pattern implementation for Doctrine2.

Knp Rad Domain Event A lightweight domain event pattern implementation for Doctrine2. Official maintainers: @Einenlum Installation With composer : $ c

A lightweight PHP paginator, for generating pagination controls in the style of Stack Overflow and Flickr.
A lightweight PHP paginator, for generating pagination controls in the style of Stack Overflow and Flickr.

PHP Paginator A lightweight PHP paginator, for generating pagination controls in the style of Stack Overflow and Flickr. The "first" and "last" page l

Laravel Package for TMDB ( The Movie Database ) API. Provides easy access to the wtfzdotnet/php-tmdb-api library.

Laravel Package for TMDB API Wrapper A Laravel package that provides easy access to the php-tmdb/api TMDB (The Movie Database) API wrapper. This packa

This package provides extended support for our spatie/enum package in Laravel.
This package provides extended support for our spatie/enum package in Laravel.

Laravel support for spatie/enum This package provides extended support for our spatie/enum package in Laravel. Installation You can install the packag

A Laravel chat package. You can use this package to create a chat/messaging Laravel application.
A Laravel chat package. You can use this package to create a chat/messaging Laravel application.

Chat Create a Chat application for your multiple Models Table of Contents Click to expand Introduction Installation Usage Adding the ability to partic

GeoLocation-Package - This package helps you to know the current language of the user, the country from which he is browsing, the currency of his country, and also whether he is using it vpn
GeoLocation-Package - This package helps you to know the current language of the user, the country from which he is browsing, the currency of his country, and also whether he is using it vpn

GeoLocation in PHP (API) 😍 😍 😍 This package helps you to know a lot of information about the current user by his ip address 😍 😍 😍 This package h

Releases(v1.2.0)
  • v1.2.0(May 3, 2022)

    What's Changed

    • [1.x] Add support for additional meta by @bensherred in https://github.com/3sidedcube/laravel-api-errors/pull/2

    Full Changelog: https://github.com/3sidedcube/laravel-api-errors/compare/v1.1.0...v1.2.0

    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Feb 9, 2022)

    What's Changed

    • [1.x] Add support for Laravel 9 by @bensherred in https://github.com/3sidedcube/laravel-api-errors/pull/1

    Full Changelog: https://github.com/3sidedcube/laravel-api-errors/compare/v1.0.0...v1.1.0

    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Dec 23, 2021)

Owner
3 SIDED CUBE
We're an app development and digital product company that specialises in tech for good.
3 SIDED CUBE
Laravel Responder - a package for building API responses, integrating Fractal into Laravel and Lumen

A Laravel Fractal package for building API responses, giving you the power of Fractal with Laravel's elegancy.

Alexander TΓΈmmerΓ₯s 776 Dec 25, 2022
This package aims to help you standardize all your API responses in a simple and structured way.

Laravel API Response This package aims to help you standardize all your API responses in a simple and structured way. By default, the stucture of the

Kode Pandai 6 Dec 6, 2022
Renders consistent HTTP JSON responses for API-based projects

Laravel API Response is a package that helps to provide and render a consistent HTTP JSON responses to API calls as well as converting and formatting

Kennedy Osaze 43 Nov 20, 2022
Caches responses as static files on disk for lightning fast page loads.

Laravel Page Cache This package allows you to easily cache responses as static files on disk for lightning fast page loads. Introduction Installation

Joseph Silber 1k Dec 16, 2022
Builds nice, normalized and easy to consume REST JSON responses for Laravel powered APIs.

REST API Response Builder for Laravel Master branch: Development branch: Table of contents Introduction Why should I use it? Usage examples Features E

Marcin Orlowski 614 Dec 26, 2022
Laravel Jsonable - Well-Formated Responses & Exceptions.

Laravel Jsonable Well-Formated Responses & Exceptions. Documentation You can find the detailed documentation here in Laravel Jsonable Documentation. C

Pharaonic 1 Aug 7, 2022
Laravel Proxy Package for handling sessions when behind load balancers or other intermediaries.

Laravel Trusted Proxies Setting a trusted proxy allows for correct URL generation, redirecting, session handling and logging in Laravel when behind a

Chris Fidao 7.3k Jan 4, 2023
This package provides new helper functions that take care of handling all the translation hassle and do it for you.

Laravel Translate Message ?? This package provides new helper functions that take care of handling all the translation hassle and do it for you. Insta

Basel Rabia 17 Feb 8, 2022
Ignition: a beautiful error page for Laravel apps

Ignition is a beautiful and customizable error page for Laravel applications running on Laravel 5.5 and newer. It is the default error page for all Laravel 6 applications.

Spatie 260 Dec 29, 2022
Your users do not always report errors, LaraBug does. LaraBug is a simple to use and implement error tracker built for the Laravel framework.

Your users do not always report errors, LaraBug does. LaraBug is a simple to use and implement error tracker built for the Laravel framework. This rep

LaraBug 197 Dec 9, 2022