Skip to content

Commit d8300eb

Browse files
author
jiannei
committed
feat: Return exception message
1 parent 06ba0c5 commit d8300eb

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

src/Support/Traits/ExceptionTrait.php

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
use Illuminate\Http\Exceptions\HttpResponseException;
1616
use Illuminate\Http\JsonResponse;
1717
use Illuminate\Http\Request;
18+
use Illuminate\Support\Arr;
1819
use Illuminate\Support\Facades\Config;
1920
use Illuminate\Validation\ValidationException;
2021
use Jiannei\Response\Laravel\Response;
@@ -33,11 +34,13 @@ protected function prepareJsonResponse($request, Throwable $e)
3334
{
3435
// 要求请求头 header 中包含 /json 或 +json,如:Accept:application/json
3536
// 或者是 ajax 请求,header 中包含 X-Requested-With:XMLHttpRequest;
37+
$isHttpException = $this->isHttpException($e);
38+
3639
return app(Response::class)->fail(
37-
'',
38-
$this->isHttpException($e) ? $e->getStatusCode() : 500,
40+
$isHttpException ? $e->getMessage() : 'Server Error',
41+
$isHttpException ? $e->getStatusCode() : 500,
3942
$this->convertExceptionToArray($e),
40-
$this->isHttpException($e) ? $e->getHeaders() : [],
43+
$isHttpException ? $e->getHeaders() : [],
4144
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
4245
);
4346
}
@@ -57,7 +60,13 @@ protected function buildFailedValidationResponse(Request $request, array $errors
5760
return (static::$responseBuilder)($request, $errors);
5861
}
5962

60-
return app(Response::class)->fail('', Config::get('response.validation_error_code', 422), $errors);
63+
$firstMessage = Arr::first($errors, null, '');
64+
65+
return app(Response::class)->fail(
66+
is_array($firstMessage) ? Arr::first($firstMessage) : $firstMessage
67+
, Config::get('response.validation_error_code', 422),
68+
$errors
69+
);
6170
}
6271

6372
/**
@@ -69,7 +78,11 @@ protected function buildFailedValidationResponse(Request $request, array $errors
6978
*/
7079
protected function invalidJson($request, ValidationException $exception)
7180
{
72-
return app(Response::class)->fail('', Config::get('response.validation_error_code', $exception->status), $exception->errors());
81+
return app(Response::class)->fail(
82+
$exception->validator->errors()->first(),
83+
Config::get('response.validation_error_code', $exception->status),
84+
$exception->errors()
85+
);
7386
}
7487

7588
/**

0 commit comments

Comments
 (0)