Getting error: ModelError: Received server error (500) error when hitting sage maker endpoint - amazon-sagemaker

`const callSageMaker = async () => {
const client = new SageMakerRuntimeClient();
let data = '0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0';
const params = {
EndpointName: process.env.SAGEMAKER_EP_NAME,
ContentType: "text/plain",
Body:'bytes',
data,
};
const command = new InvokeEndpointCommand(params);
try {
const data = await client.send(command);
return data;
} catch (error) {
// error handling.
console.log('error catch',{ error });
return error;
}
}`
I am hitting this sageMaker endpoint but getting this error
` {
error: ModelError: Received server error (500) from primary with message "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
500 Internal Server Error
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
{
'$fault': 'client',
'$metadata': {
httpStatusCode: 424,
extendedRequestId: undefined,
cfId: undefined,
attempts: 1,
totalRetryDelay: 0
},
OriginalStatusCode: 500,
OriginalMessage: '\n' +
'500 Internal Server Error\n' +
'Internal Server Error\n' +
'The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.\n',
ErrorCode: 'INTERNAL_FAILURE_FROM_MODEL'
}
}`

I was sending the data incorrectly correct format was
params{
Body:data
}

Related

Getting status 400 as an error instead of json response

I have a front-end connected to back-end, using http requests.
I'm experiencing this thing where if I return res.status(200) I get a response which I can send with that response a message. But when I'm sending res.status(400). I'm getting an red error on console rather than a parsable response.
app.post('/new', (req, res) => {
const { fullname, phone, country, img } = req.body
return res.status(200).json({
title: 'Ok, we got you!'
})
})
// If I'm changing that status to 400 I get that red error on console and I cannot parse from it anything (anything atleast that I want)
Yes, and that's the correct behaviour with HTTP requests. HTTP 400 Bad Request indicates an error rather then a successful response from your web server. So you need to catch the error thrown by the server with either a .catch() clause or a try/catch block in order to access the data returned on your client side. You're server code is absolutely fine. Just add the code below to your client side application.
Using .catch approach
axios.get('/foo')
.catch(function(error) {
console.log(error.response.data);
console.log(error.response.data.title); // your title
console.log(error.response.status);
console.log(error.response.headers);
});
Using try/catch approach
try {
const resp = await axios.get('/foo');
} catch (error) {
console.log(error.response.data);
console.log(error.response.data.title); // your title
console.log(error.response.status);
console.log(error.response.headers);
}
For more information visit this link

React-Apollo catch when server is down

In my React ApolloGraphQL app with a node server, I'm trying to have it catch errors when my node server is down. All works great and normal when the node server us up... graphQL errors are caught and displayed. But when I stop the node server, I get a runtime error that I can't avoid. When the node server is down, the server responds with a 503 Service Unavailable response and an html page that isn't JSON.
The apollo client is set up like this:
const client = new ApolloClient({
assumeImmutableResults: true,
fetchOptions: {
credentials: "include"
},
fetch: fetch,
onError: ({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.log(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,),);
if (networkError) {console.log(`[Network error]: ${networkError}`);}
response = {errors:null};
},
cache: new InMemoryCache({
freezeResults: true,
dataIdFromObject: obj => {
let dataId = null;
switch (obj.__typename) {
default:
dataId = defaultDataIdFromObject(obj);
}
return dataId;
},
cacheRedirects: {
Query: {
productVariant: (_, args, { getCacheKey }) => {
const cacheKey = getCacheKey({ __typename: "ProductVariant", ...args });
return cacheKey;
}
}
},
}),
});
The above onError block response with this message:
Error: Network error: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I have the mutation set up this way:
const [mutateVariant, {data, error, loading}] = useMutation(UPDATE_PRODUCT_META);
And I call it like so:
mutateVariant({ variables: {inputM: {...buildMetaInput(editedData)} },
errorPolicy: 'ignore', onError: (error) => Logger("Error:", error)});
You can see I've tried it with different errorPolicy settings and adding an onError callback.
But I keep getting unhandled runtime errors and don't seem to be able to catch and handle them:
Unhandled Runtime Error
Error: Network error: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Call Stack
ApolloError webpack-internal:///./node_modules/apollo-client/bundle.esm.js (76:28)
error webpack-internal:///./node_modules/apollo-client/bundle.esm.js (1041:48)
notifySubscription webpack-internal:///./node_modules/zen-observable/lib/Observable.js (140:18)
onNotify webpack-internal:///./node_modules/zen-observable/lib/Observable.js (179:21)
error webpack-internal:///./node_modules/zen-observable/lib/Observable.js (240:15)
error/< webpack-internal:///./node_modules/apollo-client/bundle.esm.js (880:76)
error webpack-internal:///./node_modules/apollo-client/bundle.esm.js (880:27)
notifySubscription webpack-internal:///./node_modules/zen-observable/lib/Observable.js (140:18)
onNotify webpack-internal:///./node_modules/zen-observable/lib/Observable.js (179:21)
error webpack-internal:///./node_modules/zen-observable/lib/Observable.js (240:15)
error webpack-internal:///./node_modules/apollo-link-error/lib/bundle.esm.js (53:34)
notifySubscription webpack-internal:///./node_modules/zen-observable/lib/Observable.js (140:18)
onNotify webpack-internal:///./node_modules/zen-observable/lib/Observable.js (179:21)
error webpack-internal:///./node_modules/zen-observable/lib/Observable.js (240:15)
createHttpLink/</</< webpack-internal:///./node_modules/apollo-link-http/lib/bundle.esm.js (92:26)
the returned error data from the useMutation hook:
graphQLErrors: Array []
message: "Network error: JSON.parse: unexpected character at line 1 column 1 of the JSON data"
​networkError: {…}
​ ​bodyText: "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>503 Service
Unavailable</title>\n</head><body>\n<h1>Service Unavailable</h1>\n<p>The server is temporarily unable
to service your\nrequest due to maintenance downtime or capacity\nproblems. Please try again later.
</p>\n<p>Additionally, a 503 Service Unavailable\nerror was encountered while trying to use an
ErrorDocument to handle the request.</p>\n</body></html>\n"
name: "ServerParseError"
​​ response: Object { }
​​ statusCode: 503
How do I catch this error?
The mutateVariant function returns a promise. Try adding a .catch() after it is called.
mutateVariant().catch(() => {...});

Access object from server response when using yield call for a blob file

So I try to make a call to the server to get a PDF file, which works when the file exist. But when there is no file, i get a 404 response from the server. I need to access this status in the result object. The problem is when the blob tries to download and it doesnt find the file, it does not provide me with the result from server, but instead it says this:
TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
If I tweak it a bit it says "Error fetching file". But I really need the status from the server response due to displaying correct info if the file does not exist or if its an server error. Due to sensitive data, I cannot copy paste the result from server in here. But it does show result: { statusCode: 404 " } in the object.
This is my code:
export function* getInvoicePDFWorkerSaga(arg) {
const {
organizationNumber, agreementId, invoiceNumber,
} = arg;
try {
const blob = yield call(invoices.getInvoicePDF, organizationNumber, agreementId, invoiceNumber);
const blobUrl = URL.createObjectURL(blob);
downloadFile(blobUrl, `invoice_${invoiceNumber}`, 'pdf');
} catch (e) {
yield put(actions.getInvoicePDFFailedAction(invoiceNumber, formatError(e)));
const retry = yield call(RetryPrompt);
if (retry) {
yield call(getInvoicePDFWorkerSaga, arg);
}
}
}
getInvoicePDF: (organizationNumber, agreementId, invoiceNumber) => (
getBlob({ url: ENDPOINTS.getInvoicePDF(organizationNumber, agreementId, invoiceNumber) })
),

Getting error: "You provided an invalid object where a stream was expected" without react-native debugger

I'm a newbie and I have the code provided below which work excellent with react-native debugger connected, but without the debugger, I'm getting the error. Error connected to that line:
return from((execute(link, operation) as unknown) as Subscribable<GraphQLResponse<{ login: User }>>)
.pipe(responseInterceptor('login'));
But I don't know how to fix it.
Full code of my request:
login(userInput: LoginInput) {
const operation = {
query: gql`
mutation Login($userInput: LoginInput) {
login(input: $userInput) {
_id
authToken
email
status
}
}
`,
variables: { userInput },
};
return from((execute(link, operation) as unknown) as Subscribable<GraphQLResponse<{ login: User }>>)
.pipe(responseInterceptor('login'));
}

Sending JSON via Postman causes an error in my Node.js service

I created schema in node.js. It worked before I included arrays.
This is my schema code:
const Item = new item_Schema({
info:{
title:{type:String, required:true},
bad_point:{type:Number, 'default':0},
Tag:{type:String, required:true}
},
review:{
Review_text:{type:Array, required:true},
Phone_list:{type:Array, required:true},
LatLng_list:{type:Array, required:true}
}
});
Item.statics.create = function(info, review){
const list = new this({
info:{
title,
bad_point,
Tag
},
review:{
Review_text,
Phone_list,
LatLng_list
}
});
return list.save();
};
This is my register code:
exports.register = (req, res) => {
const { info, review } = req.body
const create = (list) => {
return Item.create(info, review)
}
const respond = () => {
res.json({
message: 'place route registered successfully'
})
}
const onError = (error) => {
res.status(409).json({
message: error.message
})
}
RouteReviewItem.findOneBytitle(title)
.then(create)
.then(respond)
.catch(onError)
}
And this is the Postman JSON raw code:
{
"info":"{
"title":"test title",
"badPoint":"0"
"Tag":"tag1"
}",
"review":"{
"Review_text":["1번리뷰", "2번리뷰", "3번리뷰"],
"Phone_list":"["010-0000-0000", "010-1111-1111", "010-2222-2222"],
"LatLng_list":["111.1111,111.1111", "222.222,222.222","333.3333,333.3333"]
}"
}
This is the error I get in Postman:
SyntaxError: Unexpected token in JSON at position 17
at JSON.parse (<anonymous>)
at parse (C:\MainServer\node_modules\body-parser\lib\types\json.js:89:19)
at C:\MainServer\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\MainServer\node_modules\raw-body\index.js:224:16)
at done (C:\MainServer\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\MainServer\node_modules\raw-body\index.js:273:7)
at emitNone (events.js:105:13)
at IncomingMessage.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1045:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
Is this a problem with postman? Or the node.js side?
I looked at the node.js book I was studying, but could not find any relevant information.
The code is fine, you have an issue with JSON you used for testing. For further testing and debugging, I suggest that you verify that the requests you send you the endpoint are correct by using a service like JSONLint (or any offlne tool that does the same). For the request you posted in the question, this service complains:
Error: Parse error on line 2:
{ "info": "{ "title": "test t
----------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
Next time, before sending a request, make sure it is correct syntactically. That way you'll know that there is a problem with your code, and won't spend time debugging a non-existent issue.

Resources