Error Handling in Service Methods #641
Replies: 3 comments
-
You can add the annotation to the service method that gets called in a controller using '@throws' annotation. So in case you annotate the service method with '@throws ModelNotFoundException' and call it in the controller, Scramble will document 404 error response. This is one of the simplest cases, if you provide your code examples, I may suggest something more automated. Let me know! |
Beta Was this translation helpful? Give feedback.
-
Hi if I add the following code snippets to the service method that is called. The error message is not displayed. /**
* @throws Illuminate\Validation\UnauthorizedException
*/ Maybe you have a more concrete example for me? |
Beta Was this translation helpful? Give feedback.
-
I'm sorry, I misguided you. You need to add Speaking of the exception you mentioned, In case you have your own exception handler or for any other reason you want it to have documented, it is very simple to implement! You just need to create <?php
namespace App\Support\Documentation;
use Dedoc\Scramble\Extensions\ExceptionToResponseExtension;
use Dedoc\Scramble\Support\Generator\Reference;
use Dedoc\Scramble\Support\Generator\Response;
use Dedoc\Scramble\Support\Generator\Schema;
use Dedoc\Scramble\Support\Type\ObjectType;
use Dedoc\Scramble\Support\Type\Type;
use Illuminate\Support\Str;
use Illuminate\Validation\UnauthorizedException;
use Dedoc\Scramble\Support\Generator\Types as OpenApiTypes;
class UnauthorizedExceptionExtension extends ExceptionToResponseExtension
{
public function shouldHandle(Type $type)
{
return $type instanceof ObjectType && $type->isInstanceOf(UnauthorizedException::class);
}
public function toResponse(Type $type)
{
$validationResponseBodyType = (new OpenApiTypes\ObjectType)
->addProperty(
'message',
(new OpenApiTypes\StringType)
->setDescription('Error overview.')
)
->setRequired(['message']);
return Response::make(403)
->description('Unauthorized')
->setContent(
'application/json',
Schema::fromType($validationResponseBodyType)
);
}
public function reference(ObjectType $type)
{
return new Reference('responses', Str::start($type->name, '\\'), $this->components);
}
} Let me know if you have any other questions! |
Beta Was this translation helpful? Give feedback.
-
We often use a service pattern to place the business logic not in the controller, but in a service, which can then be called in several places.
As far as I can see and have tried, only abort_if methods are recognized in the controller. Is it also planned to recognize in deeper levels?
Application sketch
Controller calls service -> Service processes database query and update and returns result to controller -> Controller answers the query
If I now determine in the database query that the ID does not exist, I call the abort command in the service.
Beta Was this translation helpful? Give feedback.
All reactions