Lumen7.x 使用笔记(六) 参数验证异常处理

341 次浏览次阅读
没有评论

Lumen7.x 使用笔记(六)参数验证异常处理

1. app\Exceptions 目录下的 Handler.php 修改代码如下

<?php  

namespace App\Exceptions;  

use App\Enums\WopCode;  
use App\Enums\WopMessage;  
use Exception;  
use Illuminate\Auth\Access\AuthorizationException;  
use Illuminate\Database\Eloquent\ModelNotFoundException;  
use Illuminate\Http\JsonResponse;  
use Illuminate\Http\Response;  
use Illuminate\Validation\ValidationException;  
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;  
use Symfony\Component\HttpKernel\Exception\HttpException;  
use Throwable;  

class Handler extends ExceptionHandler  
{  
  /**  
 * A list of the exception types that should not be reported. * * @var array  
 */  
 protected $dontReport = [  
    AuthorizationException::class,  
    HttpException::class,  
    ModelNotFoundException::class,  
    ValidationException::class,  
];  

  /**  
 * Report or log an exception. * * This is a great spot to send exceptions to Sentry, Bugsnag, etc. * * @param Throwable $exception  
  * @return void  
 * @throws Exception  
 */  
 public function report(Throwable $exception)  
 {parent::report($exception);  
 }  

  /**  
 * Render an exception into an HTTP response. * * @param $request  
  * @param Throwable $exception  
  * @return Response|JsonResponse  
 * @throws Throwable  
 */  
 public function render($request, Throwable $exception)  
 {if ($exception instanceof ValidationException) {$errorInfo = array_slice($exception->errors(), 0, 1, false);  
    $msg = array_column($errorInfo, 0);  
    $content = [  
    'code' => WopCode::PARAMS_FAILED,  
    'msg' => $msg,  
   ];  
     return response($content);  
} elseif($exception instanceof HttpException) {  
   $content = [  
   'code' => WopCode::ERROR,  
   'msg' => WopMessage::MISS_REQUIRED_PARAMS,  
   ];  
   return response($content);  
} else {  
  $content = [  
  'code' => WopCode::ERROR,  
  'msg' => $exception->getMessage(),];  
  return response($content);  
  }  
 }}

控制器写法

 public function register(Request $request)
    {
        $this->validate($request,  ['phone' => 'required|regex:/^1[3456789]\d{9}$/',
                'password' => 'required',
        ]);
        return $this->userService->registerService($request->all());
    }
正文完
 0
评论(没有评论)