Handle api exception cakePHP 4

  • September 7, 2022
  • 451

Khi sử dụng cakePHP viết api nếu có lỗi xãy ra, mặc đinh cakePHP sẽ trả về error theo dạng template html. Như vậy response trả về khi api gặp lỗi sẽ bị sai định dạng. Hôm nay, chúng ta sẽ handle lại error & exception cho api đúng chuẩn.
Ở bài viết trước chúng ta đã viết api lấy tất cả các users auth with JWT token. Nhưng nếu truyền token sai đinh đạng response trả về sẽ là html.

api error

Define handle error

Định nghĩa các config hanle error trong file config/app.php. Thêm config handle error với class ApiExceptionRenderer


   'Error' => [
        'errorLevel' => E_ALL,
        'exceptionRenderer' => 'App\Error\ApiExceptionRenderer',
        'skipLog' => [
            'Cake\Http\Exception\MissingControllerException',
            'Cake\Controller\Exception\MissingActionException',
            'Cake\Routing\Exception\MissingRouteException',
            'Cake\Http\Exception\BadRequestException',
        ],
        'log' => true,
        'trace' => true,
        'ignoredDeprecationPaths' => [],
    ],

Custom Api ExceptionRenderer

Tạo class ApiExceptionRenderer trong thư mục src/Error để handle response khi api bị lỗi


<?php
declare(strict_types=1);

namespace App\Error;

use Cake\Error\ExceptionRenderer;
use Psr\Http\Message\ResponseInterface;

/**
 * Class AppExceptionRenderer.
 *
 * @package App\Error
 */
class ApiExceptionRenderer extends ExceptionRenderer
{
    /**
     * Render error json view.
     *
     * @return \Psr\Http\Message\ResponseInterface
     */
    public function render(): ResponseInterface
    {
        $exception = $this->error;
        $code = $this->getHttpCode($exception);
        $message = $this->_message($exception, $code);
        $method = $this->_method($exception);
        $template = $this->_template($exception, $method, $code);
        $response = $this->controller->getResponse();
        $this->controller->setResponse($response->withStatus($code));
        $this->controller->set([
            'status' => false,
            'data' => [],
            'error' => [
                'code' => $code,
                'message' => $message,
            ],
        ]);
        $this->controller->viewBuilder()->setOption('serialize', ['status', 'data', 'error']);

        return $this->_outputMessage($template);
    }
}

Define api error json response

Đinh nghĩa lại response trả về là json khi api có lỗi trong file src/Controller/ErrorController.php


/**
     * Initialization hook method.
     *
     * @return void
     */
    public function initialize(): void
    {
        $this->loadComponent('RequestHandler');
        if (strpos($this->_templatePath(), 'Api') !== false) {
            $this->RequestHandler->renderAs($this, 'json');
        }
    }

Nhưng vậy là chúng ta đã handle được expception cho api khi sử dụng cakePHP, giờ kiểm tra lại response api get users.
Handle error api
Việc handle response error khi viết api là vô cùng quan trọng khi viết RESTFUL API. Hi vọng bài viết giúp ích được cho bạn. Thanks for reading...