How to catch 422 Unprocessable entry in laravel 5.5.16 - api

How to catch 422 Unprocessable entry in laravel 5.5.16 ?
I am getting below error message while I am sending http://127.0.0.1:8000/api/topics API request.
I would like to customize this error.In this regard I would like to know Which class and function producing this error and their location.

A 422 Error is thrown when Laravel validates your Request data and the data is wrong, invalid or not processable.
If you are validating your data in an extra Request class, you can add a message method to override the error messages (further info here):
/**
* Get the error messages for the defined validation rules.
*
* #return array
*/
public function messages()
{
return [
'body.required' => 'A message is required',
];
}
If you are validating the data inside your Controller through $request->validate(...), you need to create an own Validator class inline with a messages argument (further info here):
$messages = [
'required' => 'The :attribute field is required.',
];
$validator = Validator::make($input, $rules, $messages);

Related

How to show input and output exemple with nelmio-api-bundle and php8.1

I'm currently trying to make an API doc page thanks to nelmio-api-bundle. I only have one route which is a POST route. I'm receiving a JSON in the body of the request and I'm using the Serializer from symfony to deserialize it in a DTO. I'm also using a DTO for the response (which contains the status code, a bool set to true or false, and a message). Now I'm trying to use these DTO (for input and output) to build the API documentation with nelmio-api-bundle but how to make it ? I'm using PHP8.1 attributes to make it, for response it almost works (except that the response is shows as an array) but I don't know how to make it for the inputs.
Here is my current code:
#[Route('/user', methods: ['POST'])]
#[OA\Parameter(
name: 'user',
description: 'The user information in JSON',
in: 'query',
required: true
)]
#[OA\Response(
response: 200,
description: 'Returns the success response',
content: new OA\JsonContent(
type: 'array',
items: new OA\Items(ref: new Model(type: SuccessResponseDTO::class))
)
)]
public function registerUser(Request $request, LoggerInterface $logger): JsonResponse
{
//the code to register the user
}
And here is the result:
Do someone know how to make it ?

How to send multiple Validation Errors to React using Flask and Marshmallow in Backend and Axios for React-Native in Frontend

I am using Marshmallow to validate incoming fields for a simple put request.
Now I am testing the error handling in the frontend to make sure I send the right error messages for the frontend.
I am usually sending data of type
{
password: string,
email: string
}
For now Marshmallow checks if the password is long enough and if the email is of format Email.
I collect all errors in a expect statement and send it to the frontend like this:
except ValidationError as err:
return make_response(
{"errors": err.messages}, status.HTTP_400_BAD_REQUEST
)
with Postman giving me e.g. this response:
{
"errors": {
"email": [
"Missing data for required field."
],
"password": [
"Missing data for required field."
],
}
}
All error messages are therefore collected within the field errors and sent back to the frontend.
When the error is sent back to the frontend I catch my error and all I get is this object:
Object {
"data": null,
"error": [Error: Request failed with status code 400],
}
How do I correctly send or receive the
errors: err.messages
field in the frontend within a make_response error response?
I found the solution to the problem I had here:
github.com/axios/axios/issues/960.
Apparently you have to access the response object or the error object that is send to axios. There is no interceptor needed. What I changed was this line, when resolving the promise to:
try {
resolved.data = await promise;
} catch (e) {
resolved.error = e.response.data;
}
before that I accessed the error with:
try {
resolved.data = await promise;
} catch (e) {
resolved.error = e;
}
The errors are stored within the response.data.

Getting 400 Bad Request Error for MSGraph's create subscription api [Error Code - ExtensionError]

Trying to create a subscription to get a channel for msgraph one drive notifications for file creation/upload.
I am hitting the URL -
https://graph.microsoft.com/v1.0/subscriptions
with proper headers and the following body -
{
"changeType": "updated",
"notificationUrl": "https://xxxxx.xxxxxxxxx.com/zzzz/qwertqwert",
"resource": "/users/{user-id}/drive/root",
"expirationDateTime": "2017-02-18T19:49:40.000Z",
"clientState": "justsomerandomstring"
}
I am getting the following response :
400 Bad Request Error
{
"error": {
"code": "ExtensionError",
"message": "Operation: Create; Exception: [Status Code: BadRequest; Reason: Bad Request]",
"innerError": {
"request-id": "2862896286-5415-4921-gbn5-8741288985",
"date": "2017-02-17T17:30:22"
}
}
}
I was making the same request 30-32 hrs back. Was getting the subscription-id as well as the file notifications on my redirection servlet.
Not able to figure out what changed. Couldn't find any helping documentation either
Got the same error here and it took me a while to find out what is the problem so I share this with you here.
Here's the working code:
$subscription = new Subscription([
'resource' => "me/mailFolders('Inbox')/messages?filter=id eq %27" . $draftEmail->getId() . '%27',
'notificationUrl' => 'https://my.domain.fr',
'changeType' => 'updated',
'expirationDateTime' => date(DATE_ISO8601, strtotime('+48 hours'))
]);
The line which was wrong for me is:
'resource' => 'me/messages/' . $draftEmail->getParentFolderId(),
And i replace it with
'resource' => "me/mailFolders('Inbox')/messages?filter=id eq %27" . $draftEmail->getId() . '%27',
I found my answer in this link: https://msdn.microsoft.com/en-us/office/office365/api/notify-rest-operations#subscribe-to-changes-in-my-mail-calendar-contacts-or-tasks
But in my opinion the "resource" parameter should be more documented on graph api documentation and the error message return must specify WHY this is a BadRequest.
Using beta api version solved my problem,
https://graph.microsoft.com/beta/subscriptions

How to handle Akka HTTP client response failure

Akka HTTP client requests return Future[HttpResponse] - how should one handle the Future failing? Just log an error or re-throw it to the supervisor?
Is there documentation of the type of errors that can be returned by thrown by the client (and hence automatically propagated to the supervisor ) as well as errors that can cause the Furure to fail.
It's matter of taste mostly. I typically convert Future[HttpResponse] to Future[Try[HttpResponse]] and then handle it as
response.flatMap { tryResp =>
tryResp match {
case Success(res) =>
res.status match {
case OK =>
// Unmarshal response here into Future[Something]
case Found =>
// Handle redirect by calling requestBlhBlah() again with anotehr URI
case _ =>
// I got status code I didn't expect so I wrap it along with body into Future failure
Unmarshal(res.entity).to[String].flatMap { body =>
Future.failed(new IOException(s"The response status is ${res.status} [${request.uri}] and response body is $body"))
}
}
case Failure(ex) =>
Future.failed(ex)
}
}
If you're using flow-based client you can also specify Decider to handle errors
val decider: Decider = {
case ex =>
ex.printStackTrace()
Supervision.Stop // Passes error down to subscriber
}
and then use it in either materializer
implicit val materializer = ActorMaterializer(ActorMaterializerSettings(system).withSupervisionStrategy(decider))(system)
or in per-flow basis via .withAttributes(ActorAttributes.supervisionStrategy(decider))
As per Future failure it's up to you how to handle it. You can convert failure to something else using recoverWith or log it in Future.onFailure.

Servlet response format for dojo xhrPost error handler

To trigger the error handler for dojo's xhrPost, is there a specific format in which the server response is to be sent? Or just setting the status code to the required error code in the HttpServletResponse object does the work.
Thanks,
RR
You only need to set the appropiate HTTP status code in the HttpServletResponse. I think anything greater than or equal to 400 will be considered an error by the XHR object.
Of course you can also send actual content in your response (via its output stream) and set its content type. You'll receive that in your handler as well:
dojo.xhrPost({
url: '/request',
load: function(data, ioargs) { /* ... */ },
error: function(error, ioargs) {
// error is a Javascript Error() object, but also contains
// some other data filled in by Dojo
var content = error.responseText; // response as text
var status = error.status; // status code
}
});
You can also get responseText and status from ioargs.xhr, which is the full XmlHttpRequest object.