我正在尝试拦截laravel中的错误,我发现了一种不错的方法:
模拟错误:
public function index(){
$users = User::all(); //<-SQL exeception here
return response()->json(['message'=>'ok'], 200);
}
app / Exceptions / Handler.php
public function report(Exception $exception)
{
dd($exception); //<-intercept my error here
parent::report($exception);
}
工作得很好,我可以做任何我想做的事,但有错误,但是当我使用try-catch块时,我的拦截器不起作用:
再次模拟错误
public function index(){
try {
$users = User::all();//<-SQL exeception here
} catch (\Throwable $th) {
error_log('Error handled');
//MyInterceptor::manuallyIntercept($th);
}
return response()->json(['message'=>'ok'], 200);
}
是否有一种干净的方法来以编程方式拦截所有已处理的错误?
答案 0 :(得分:0)
不是报告方法,您需要在List<WebElement> rows = StockWatchlistElements.lnkaStockWatchlist(driver);
int count = rows.size();
System.out.println("ROW COUNT : " + count);
上使用渲染方法
您将看到Handler.php
,它将仅返回JSON响应。我只想展示主要思想。
$this->errorResponse
错误响应方法
public function render($request, Exception $exception)
{
if ($exception instanceof ValidationException) {
return $this->convertValidationExceptionToResponse($exception, $request);
}
if ($exception instanceof ModelNotFoundException) {
$modelName = strtolower(class_basename($exception->getModel()));
return $this->errorResponse("Does not exists any {$modelName} with the specified identificator", 404);
}
if ($exception instanceof AuthenticationException) {
return $this->unauthenticated($request, $exception);
}
if ($exception instanceof AuthorizationException) {
return $this->errorResponse($exception->getMessage(), 403);
}
if ($exception instanceof MethodNotAllowedHttpException) {
return $this->errorResponse('The specified method for the request is invalid', 405);
}
if ($exception instanceof NotFoundHttpException) {
return $this->errorResponse('The specified URL cannot be found', 404);
}
if ($exception instanceof HttpException) {
return $this->errorResponse($exception->getMessage(), $exception->getStatusCode());
}
if ($exception instanceof QueryException) {
$errorCode = $exception->errorInfo[1];
if ($errorCode == 1451) {
return $this->errorResponse('Cannot remove this resource permanently. It is related with any other resource', 409);
}
}
if (config('app.debug')) {
return parent::render($request, $exception);
}
return $this->errorResponse('Unexpected Exception. Try later', 500);
}