異常錯誤資訊處理

expectedSelf發表於2019-12-16
use Illuminate\Http\Exceptions\HttpResponseException;
use Symfony\Component\HttpKernel\Exception\HttpException;
class ValidateException{
    /** 定義錯誤資訊json,可針對邏輯上的問題或驗證丟擲此錯誤來終止程式
     * @param string $massage
     * @param int $code
     */
    public static function abnormal($msg = 'error', $code = 400){
         $response = response()->json([
              'code' => $code,
              'msg' => $msg,
          ],$code);
      throw new HttpResponseException($response);
    }

    /** 丟擲異常,header狀態碼同code
     * @param string $massage
     * @param int $code
     */
    public static function throwOut($massage = 'error', $code = 400){
        throw new HttpException($code, $massage);
    }
}

返回的錯誤資訊格式,響應頭header 狀態碼同 code

{
    'code'  => 400,
    'msg'  => '錯誤資訊',
}

FormRequest 中重寫 failedValidation 方法,表單驗錯誤資訊簡單化

use App\Exceptions\ValidateException;
use Illuminate\Contracts\Validation\Validator;
class FormRequest{
    protected function failedValidation(Validator $validator)
    {
        $error = $validator->errors()->first();
        ValidateException::abnormal($error,400);
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
所幸無礙

相關文章