예외 처리

설정

config/exception.php

return [
    // 여기에서 예외 처리 클래스를 설정하십시오.
    '' => support\exception\Handler::class,
];

다중 애플리케이션 모드에서 각 애플리케이션에 대해 별도로 예외 처리 클래스를 설정할 수 있습니다. 자세한 내용은 다중 애플리케이션을 참조하십시오.

기본 예외 처리 클래스

webman에서 예외는 기본적으로 support\exception\Handler 클래스에 의해 처리됩니다. 기본 예외 처리 클래스를 변경하려면 구성 파일 config/exception.php를 수정하십시오. 예외 처리 클래스는 Webman\Exception\ExceptionHandlerInterface 인터페이스를 구현해야 합니다.

interface ExceptionHandlerInterface
{
    /**
     * 로그 기록
     * @param Throwable $e
     * @return mixed
     */
    public function report(Throwable $e);

    /**
     * 렌더링 반환
     * @param Request $request
     * @param Throwable $e
     * @return Response
     */
    public function render(Request $request, Throwable $e) : Response;
}

응답 렌더링

예외 처리 클래스의 render 메소드는 응답을 렌더링하는 데 사용됩니다.

구성 파일 config/app.php에서 debug 값이 true인 경우(이하 app.debug=true), 상세한 예외 정보가 반환되고, 그렇지 않으면 요약된 예외 정보가 반환됩니다.

요청이 json 반환을 기대하는 경우 반환되는 예외 정보는 json 형식으로 반환되며, 비슷한 형식입니다.

{
    "code": "500",
    "msg": "예외 정보"
}

app.debug=true인 경우 json 데이터에는 추가로 trace 필드가 포함되어 상세한 호출 스택이 반환됩니다.

기본 예외 처리 로직을 변경하고자 하는 경우 자신의 예외 처리 클래스를 작성할 수 있습니다.

비즈니스 예외 BusinessException

때때로 특정 중첩 함수에서 요청을 중단하고 클라이언트에게 오류 정보를 반환하고 싶을 때 BusinessException을 던짐으로써 이 작업을 수행할 수 있습니다.
예를 들어:

<?php
namespace app\controller;

use support\Request;
use support\exception\BusinessException;

class FooController
{
    public function index(Request $request)
    {
        $this->chackInpout($request->post());
        return response('hello index');
    }

    protected function chackInpout($input)
    {
        if (!isset($input['token'])) {
            throw new BusinessException('파라미터 오류', 3000);
        }
    }
}

위의 예시는 다음과 같은 응답을 반환합니다.

{"code": 3000, "msg": "파라미터 오류"}

주의
비즈니스 예외 BusinessException은 비즈니스 상의 try로 포착할 필요가 없으며, 프레임워크가 자동으로 포착하여 요청 유형에 따라 적절한 출력을 반환합니다.

사용자 정의 비즈니스 예외

위 응답이 귀하의 요구와 일치하지 않는 경우, 예를 들어 msgmessage로 변경하고 싶다면 MyBusinessException을 사용자 정의할 수 있습니다.

app/exception/MyBusinessException.php를 새로 생성하고 아래 내용을 추가하십시오.

<?php

namespace app\exception;

use support\exception\BusinessException;
use Webman\Http\Request;
use Webman\Http\Response;

class MyBusinessException extends BusinessException
{
    public function render(Request $request): ?Response
    {
        // json 요청 시 json 데이터 반환
        if ($request->expectsJson()) {
            return json(['code' => $this->getCode() ?: 500, 'message' => $this->getMessage()]);
        }
        // 비-json 요청 시 페이지 반환
        return new Response(200, [], $this->getMessage());
    }
}

이렇게 비즈니스 호출 시

use app\exception\MyBusinessException;

throw new MyBusinessException('파라미터 오류', 3000);

json 요청은 아래와 같은 형식의 json 응답을 받게 됩니다.

{"code": 3000, "message": "파라미터 오류"}


BusinessException 예외는 비즈니스 예외(예: 사용자 입력 파라미터 오류)로서 예측할 수 있으므로, 프레임워크는 이를 치명적인 오류로 간주하지 않으며 로그를 기록하지 않습니다.

요약

현재 요청을 중단하고 클라이언트에게 정보를 반환하고 싶을 때는 BusinessException을 사용하는 것을 고려할 수 있습니다.