I'm trying to the customzing the error format structure .for the Rest API - mongodb

I'm trying to customize the error format with the below structure but not able to set the the error and httpCodeMessage
Error Fromat :
[
{
"headers": {},
"body": {
"timestamp": "2020-08-17T10:22:14.538+0000",
"error": null,
"message": "User Not Found in the system",
"path": "/claims/search/",
"httpCodeMessage": null
},
"statusCode": "BAD_REQUEST",
"statusCodeValue": 400
}
]
#ExceptionHandler(ValidationException.class)
public ResponseEntity<ErrorResponse[]> process(ValidationException ex, HttpServletRequest req) {
return new ResponseEntity(Arrays.asList(generateErrorResponse(ex, req)), HttpStatus.BAD_REQUEST);
}
private Object generateErrorResponse(ValidationException ex, HttpServletRequest req) {
ErrorResponse error = new ErrorResponse();
if (ex.getMessage().equalsIgnoreCase("Resource Not Found")) {
error.setTimestamp(new Date());
error.setMessage(NOT_FOUND.value(), ex.getMessage());
error.setPath(req.getRequestURI().toString());
error.setError(ResponseEntity.status(NOT_FOUND));
return ResponseEntity.status(NOT_FOUND).body(error);
}
}
Can anyone suggest how to get the error and httpCodeMessage values .Is it possible to remove the statusCode and statusCodeValue attributes.

You normally have to go to the original HttpClientErrorException and getRawStatusCode() to get the HTTP error code
javadoc

Related

Linkedin Api to delete creative unable to call (getting 500)

Trying to make a call to linkedin api https://learn.microsoft.com/en-us/linkedin/marketing/integrations/ads/account-structure/create-and-manage-creatives-new?view=li-lms-2022-10&tabs=http#delete-a-creative
to delete a creative however am receiving a 500 error
{
"code": "GATEWAY_INTERNAL_ERROR",
"message": "Gateway Internal Error"
}
body of the request is:
"patch": {
"$set": {
"status": "PENDING_DELETION"
}
}
}
as per the documentation passed the header
X-RestLi-Method
as
DELETE
The issue was field name
"intendedStatus": "PENDING_DELETION"

AWS AppSync not displaying custom error properties with in Lambda Resolver ResponseMappingTemplate

We are trying to use custom error status codes with GraphQL so that our upstream services can better utilize the errors thrown.
We have a simple error class that extends the base Error class to include a status code:
export class ErrorWithStatusCode extends Error {
public statusCode: number;
constructor({
message,
name,
statusCode,
}: {
message: string;
name: string;
statusCode: number;
}) {
super(message);
this.name = name;
this.statusCode = statusCode;
}
}
export class BadRequestError extends ErrorWithStatusCode {
constructor(message: string) {
super({
message,
name: `BAD_REQUEST`,
statusCode: 400,
});
}
}
And then we throw that error in our code like so:
if (existingResource) {
throw new BadRequestError('An account with the email address already exists');
}
Inside our logs we see the Lambda invoke error:
2022-04-29T13:42:56.530Z 0e1688ac-89f1-46a7-b592-d6aeceb83fd7 ERROR Invoke Error
{
"errorType": "BAD_REQUEST",
"errorMessage": "An account with the email address already exists",
"name": "BAD_REQUEST",
"statusCode": 400,
"stack": [
"BAD_REQUEST: An account with the email address already exists",
" at Runtime.main [as handler] (/var/task/index.js:26908:19)",
" at processTicksAndRejections (internal/process/task_queues.js:95:5)"
]
}
Then in our VTL template, we just associate all properties outside of name and message to the custom errorInfo object as described here
$util.error(String, String, Object, Object)
Throws a custom error. This can be used in request or response mapping templates if the
template detects an error with the request or with the invocation
result. Additionally, an errorType field, a data field, and a
errorInfo field can be specified. The data value will be added to the
corresponding error block inside errors in the GraphQL response. Note:
data will be filtered based on the query selection set. The errorInfo
value will be added to the corresponding error block inside errors in
the GraphQL response. Note: errorInfo will NOT be filtered based on
the query selection set.
#if (!$util.isNull($ctx.error))
$utils.error($ctx.error.errorMessage, $ctx.error.name, $ctx.result, $ctx.error)
#end
$utils.toJson($ctx.result)
But when we get the error back from AppSync (using the console), we do not have any additional error properties:
{
"data": null,
"errors": [
{
"path": [
"createResource"
],
"data": null,
"errorType": null,
"errorInfo": {
"message": "An account with the email address already exists",
"type": "Lambda:Unhandled"
},
"locations": [
{
"line": 2,
"column": 5,
"sourceName": null
}
],
"message": "A custom error was thrown from a mapping template."
}
]
}

wiremock request matching from key=value pair

I am using json mapping to match the request. The request coming as content-type application/x-www-form-urlencoded which means as a Key=value pair and the value contains xml data. For example:
REQUEST=<?xml version="1.0" encoding="UTF-8"?>
<n:request xmlns:n="schema uri" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="schema location">
<header userId="userId" password="password" requesterId="123" version="100" language="de">
<product>xxx</product>
</header>
<subject>
<party externalIdentifier="1">
<address externalIdentifier="11">
<person>
<firstName>rinku</firstName>
<lastName>chy</lastName>
<birthDate>1973-12-10</birthDate>
</person>
<street>street</street>
<number>12</number>
<countryCode>de</countryCode>
<zipCode>123</zipCode>
<city>city</city>
</address>
</party>
</subject>
</n:request>
The purpose is to find the product name and the person's name. I have tried both xpath as well as query parameters expression to match the request as stated in http://wiremock.org/docs/request-matching/. But couldn't manage to get a solution yet.For example
{
"request": {
"method": "POST",
"urlPattern": "/mock.*",
"queryParameters": {
"product": {
"matches": "xxx"
}
},
// tried both seperately
"bodyPatterns": [
{
"matchesXPath": "//*[local-name()='request']/*[local-name()='header']/*[local-name()='product'][text()='xxx']"
}
]
},
"response": {
"status": 200,
"bodyFileName": "response.xml",
"headers": {
"Content-Type": "text/xml; charset=UTF-8",
"Content-Location": "response.xml"
}
}
}
Always getting the same error "[WireMock] (qtp2017957857-34) Warning: failed to parse the XML document. Reason: Content is not allowed in prolog.
Can anyone have a clue how to match such a request?
I found the solution. There is an option to intercept and modify requests. Visit -> http://wiremock.org/docs/extending-wiremock/ in the section "Intercepting and modifying requests".
public class RequestFilter extends StubRequestFilter {
#Override
public RequestFilterAction filter(Request request) {
// removed "REQUEST=" from request body
Request modifyRequest = RequestWrapper.create()
.transformBody(requestBody -> Body.fromOneOf(null, requestBody.asString().substring(8)), null, null))
.wrap(request);
return RequestFilterAction.continueWith(modifyRequest);
}
#Override
public String getName() {
return "my-request-filter";
}}

How to validate response in Postman?

I am trying to validate response body including errors in postman. How can I validate the response and text below?
{
"responseHeader": {
"publisherId": "12345",
"responseId": "abbcb15d79d54f5dbc473e502e2242c4abbcb15d79d54f5dbc473e502e224264",
"errors": [
{
"errorCode": "1004",
"errorMessage": "XXXX Not Found"
}
]
}
}
These are my tests which are failing:
tests['response json contains responseHeader'] = _.has(responseJSON, 'responseHeader');
tests['response json contains errors'] = _.has(responseJSON, 'responseHeader.publisherId');
tests["Response has publisher id"] = responseJSON.publisherId === 10003;
In the "Test" tab, parse your response body into an object, then use JavaScript to perform your tests.
var data = JSON.parse(responseBody);
tests["publisherId is 12345"] = data.responseHeader.publisherId === "12345";
Take a look at the test examples at the Postman site:
https://www.getpostman.com/docs/postman/scripts/test_scripts
https://www.getpostman.com/docs/postman/scripts/test_examples

Sails shows no error when model validation fails

in my production environment that uses MongoDB, whenever a model validation fails it shows nothing, while on my development environment with no database it shows something like this:
{
"error": "E_VALIDATION",
"status": 400,
"summary": "10 attributes are invalid",
"model": "Restaurant",
"invalidAttributes": {...}
}
I need my API to show these validation errors.
You can return validation error as response:
For example (inside controller):
create: function (req, res, next) {
......
User.create(data, function userCreated(err, user) {
if (err)
return res.negotiate(err);
return res.ok({ user: user });
}
}