A weird Error object is being logged to console - node.js

I am trying to post comments through the youtube API, but they are returning an error upon trying.
When I log the error object I get
{ [Error: Bad Request] code: 400 }
The first part of which looks weird (key-value inside array?)
I tried to log the keys of the object and it only returns code
Supposely the API return a much more detailed message, but it's like it's 'hidden' inside the [Error: Bad Request], which I dont know how to access

That's just how Node formats errors.
Try it yourself in a node console:
var e = new Error("Test");
e.code = 500
console.log(e); // Outputs: { [Error: Test] code: 500 }
As far as your issue with the YouTube API, I suggest creating a different question on StackOverflow about your issues, providing more information around how you are calling the API.

Related

Office.context.mailbox.item.body.getAsync returns error 9020 An internal error has occured

I am using a tutorial that gets the email email properties using Outlook Add-in and now I am trying to get the email body. All the research I am getting is using mostly this statement to get it.
function getEmailBody() {
Office.context.mailbox.item.body.getAsync(Office.CoercionType.Text, function callback(asyncResult) {
return asyncResult.value;
});
But when I run it, it returns empty and when I put a debugger on it, the asyncResult has these values:
value: null
status: failed
error: OSF.DDA.Error
name: GenericResponseError
message: An internal error has occurred.
code: 9020
Does anyone knows what is causing this error? I am using outlook.office.com in Google Chrome to access the emails.

How to add custom paramater in error object lb4?

I am using strongloop 4 (lb4). I am facing one issue that in error object I need to one more custom parameter in the error object.
I want it on the global level. On every error, I want to add that custom parameter in every error message.
In loopback4 global error handling is done by src/sequence.ts.
Suppose the error message object is.
{
"error": {
"statusCode": 400,
"name": "xyz",
"message": "firstName is required"
}
}
I want error object output like.
{
"error": {
"customParam" : "customParam",
"statusCode": 400,
"name": "xyz",
"message": "firstName is required"
}
}
Cross-posting the answer I gave on GitHub in https://github.com/strongloop/loopback-next/issues/1867#issuecomment-434247807
Building HTTP error responses is a tricky business. It's easy to get it wrong and open your application to attacks.
In LoopBack (both 3.x and 4.x), we use our strong-error-handler middleware to take care of this. See Handling Errors in our docs.
Here are the important security constraints to keep in mind:
In production mode, strong-error-handler omits details from error responses to prevent leaking sensitive information:
For 5xx errors, the output contains only the status code and the status name from the HTTP specification.
For 4xx errors, the output contains the full error message (error.message) and the contents of the details property (error.details) that ValidationError typically uses to provide machine-readable details about validation problems. It also includes error.code to allow a machine-readable error code to be passed through which could be used, for example, for translation.
In debug mode, strong-error-handler returns full error stack traces and internal details of any error objects to the client in the HTTP responses.
Now that I have warned you, LoopBack 4 makes it very easy to format the error messages your way. Just provide a custom implementation of the Sequence action reject. See Customizing Sequence Actions in our docs, it explain how to create a custom send action. The solution for reject is pretty much the same, you just need a different signature for the action function.
export class CustomRejectProvider implements Provider<Reject> {
// ...
action({request, response}: HandlerContext, error: Error) {
// handle the error and send back the error response
// "response" is an Express Response object
}
}
Caveat: some errors thrown by LB4 have only code set, these errors need a bit of pre-processing to decide what HTTP status code they should trigger. (For example, the error code ENTITY_NOT_FOUND should be mapped to the status code 404). The built-in reject action does not yet expose this pre-processing for consumption by custom reject actions. It's an oversight on our side, l created a new issue https://github.com/strongloop/loopback-next/issues/1942 to keep track of that.
I tried adding error object into new object.
let error = new Error();
error.name = 'Invalid_OTP_AttemptsError';
error.status = 422;
error.message = 'You’ve exceeded the maximum number of One-Time Password (OTP) attempts';
let data={...error};
data.retryCount=foundMb.retryCount
data.resendCount=foundMb.resendCount
return callback(null,data);

What is considered standard when dealing with database errors in a REST application?

I'm currently writing a public REST service in Node.js that interfaces with a Postgres-database (using Sequelize) and a Redis cache instance.
I'm now looking into error handling and how to send informative and verbose error messages if something would happen with a request.
It struck me that I'm not quite sure how to handle internal server errors. What would be the appropriate way of dealing with this? Consider the following scenario:
I'm sending a post-request to an endpoint which in turn inserts the content to the database. However, something went wrong during this process (validation, connection issue, whatever). An error is thrown by the Sequelize-driver and I catch it.
I would argue that it is quite sensitive information (even if I remove the stack trace) and I'm not comfortable with exposing references of internal concepts (table-names, functions, etc.) to the client. I'd like to have a custom error for these scenarios that briefly describes the problem without giving away too detailed information.
Is the only way to approach this by mapping every "possible" error in the Sequelize-driver to a generic one and send that back to the client? Or how would you approach this?
Thanks in advance.
Errors are always caused by something. You should identify and intercept these causes before doing your database operation. Only cases that you think you've prepared for should reach the database operation.
If an unexpected error occurs, you should not send an informative error message for security reasons. Just send a generic error for unexpected cases.
Your code will look somewhat like this:
async databaseInsert(req, res) {
try {
if (typeof req.body.name !== 'string') {
res.status(400).send('Required field "name" was missing or malformed.')
return
}
if (problemCase2) {
res.status(400).send('Error message 2')
return
}
...
result = await ... // database operation
res.status(200).send(result)
} catch (e) {
res.status(500).send(debugging ? e : 'Unexpected error')
}
}

How do I init XOD in WebViewer? "DisplayModes" is undefined

I'm trying to load a XOD document into a PDFTron WebViewer. As far as I can read in the documentation and samples, this should be a simple "plug and play"-operation - it should simply work when you point at a file. Ideally, in my example, the document should be fetched from a service, as so:
fetch('/myservice/GetXOD')
.then(function(data) {
$(function() {
var viewerElement = document.getElementById("viewer");
var myWebViewer = new PDFTron.WebViewer({
initialDoc: data.body
}, viewerElement);
});
});
Unfortunately I get the following error:
Uncaught TypeError: Cannot read property 'DisplayModes' of undefined
The reason I'm doing it in a fetch, is because I'm rendering a Handlebars template, and pass the data to instantiate in a callback. However, I've isolated the code into an otherwise "empty" HTML-document, and in the simplified example below, I'm simply pointing at the XOD provided by PDFTron on page load (no fetch this time).
$(function() {
var viewerElement = document.getElementById("viewer");
var myWebViewer = new PDFTron.WebViewer({
initialDoc: 'GettingStarted.xod' // Using the XOD provided by PDFTron
}, viewerElement);
});
This unfortunately returns a different error (HTTP status 416).
Uncaught Error: Error loading document: Error retrieving file: /doc/WebViewer_Developer_Guide.xod?_=-22,. Received return status 416.
The same error appears when I run the samples from PDFTron on localhost.
I'm at a complete loss of how I should debug this further - all the samples assume everything is working out of the box.
I should note that I can actually get PDFs working just fine on localhost, but not on the server. XODs are problematic both on the server and on localhost.
I'm sorry to hear you are having troubles running our samples.
Your error message says 416 which means "Requested range not satisfiable". Perhaps your development servers do not support byte range requests (https://en.wikipedia.org/wiki/Byte_serving).
Could you try passing an option streaming: true? When streaming is true you're just requesting the entire file up front which shouldn't be a problem for any servers but it is a problem for WebViewer if the file is large because it will need to be completely downloaded and parsed at the start which is slow.

NodeJS / ExpressJS: Syntax error unexpected end of file

One of my NodeJS / ExpressJS app gets quite from time to time by the error:
SyntaxError: Unexpected end of input
at parse (native)
Unfortunately there is no line number and no stack. The hole project is based on typescript and compiles just fine. The process is running on a PM2.
Any idea how to hunt down this error?
Regards and thx...
Search your app source code for JSON.parse, then find if any of the input your are getting is a proper JSON. I suspect you are getting HTML page as a response for one of your requests (due to 404 or 5xx)
To track down the error:
try{
JSON.parse(body);
}
catch(err){
console.log('error due to ', err);
}

Resources