Node express return message with link - javascript

I've node program which in case of error needs to send error message ,
this works, however I want to add to the message also a link.
something like
Something went wrong and we cannot open your application.
Follow this tutorial to proceed.
And the this tutorial will be a link e.g. https://nodejs.org/en/about/
How can I do that?
...
} catch (e) {
throw new Error('Something went wrong and we cannot open your application.Follow this tutorial to proceed.'
)
}
And I send the data via express like res.send
app.get('/', async function (req, res) {
try {
const url = await invokeApp()
} catch (e) {
res.send(e.message)
}
})
update
while trying the suggestion below I able to get the link but the messege order was changed, any idea how to fix it ?
} catch (e) {
throw new Error('Something went wrong and we cannot open your application.Follow this tutorial to proceed.'
)
}

try this:
...
} catch (e) {
throw new Error('Something went wrong and we cannot open your application. Follow this tutorial to proceed.')
}
You can use res.send with html string -- i.e res.send('<p> html </p>') - and deal with on the other side.

Try this
res.json({ err : e.message , link : "error/url"})
and if error comes you could acces url from this object and display the link in front end.

Related

How to find the Error message in Error object send by NodeJS in Angular

The Nodejs functions return an error from try/catch scope, such as the one below if the user doesn't exist of if a database is not reachable:
router.delete('/delete/:email', async (req, res) => {
var email = req.params.email;
try {
let result = await User.remove({"email": email});
res.status(204).send(email);
} catch (err) {
res.status(400).send(err);
}
});
I can also return the Error from Nodejs server by myself:
return res.status(400).send(new Error(`The user with email ${email} doesn't exist.`));
The first problem is that I can't find the error message that is embedded somewhere deep in the body the returned Error object. It is stored in one of its 100+ attributes. Where should I look for it so I could display in on a screen for the end user to read it?
Then, the err object generated by the try/catch scope has a set of different attributes comparing to the Error object created with new Error("Here is my error message"). Is there a way to normalize the returned Errors so they all have the same or similar attributes?
You don't need to return the whole error object from the server, and arguably shouldn't since error messages can expose internals about your code and infrastructure.
One way you could handle this is to format and return an error message from the server yourself. Assuming you're using express this would look something like:
return res.status(400).json({ message: `The user with email ${email} doesn't exist.` });
Alternatively you could use an error handling middleware like strong-error-handler found here: https://github.com/strongloop/strong-error-handler which automatically builds a json formatted message that's easier to parse, but keep in mind that the content of the message differs depending on whether you set debug mode to true or no.
If you want to develop a secure web application with nice error handling, i will suggest you the following structure.
Step 1. At front end divide your api calls in four main operations for e.g. inset,update,query and filter.
now whenever your page loads and you want to show some data fetched from server then your api call must be like 'https://domainname.tld/server/query' and send some payload with this api call according to need of your data requirements to be fetched.
At backend probably at Server.js handle like this :
app.all("/server/query", function (req, res) {
try {
console.log(a);
// some database or io blocking process
} catch (error) {
// error handling
var err = writeCustomError(error.message || error.errmsg || error.stack);
res.status(417).json(err).end();
}
});
function writeCustomError(message) {
var errorObject = {};
errorObject.message = message;
errorObject.code = 10001; // as you want
errorObject.status = "failed";
return errorObject;
}
in try block you can also handle logical errors using same function i.e writeCustomError
So if you use this approach you can also implement end-to-end encryption and send only eP('encrypted payload') and eK('encryption Key'),by doing this end users and bad end users even can not evaluate your serve API calls.
If you are thinking how will you route different paths at server then simplest solution is send uri in payload from client to server for e.g
User wants to reset password :-
then
call api like this
https://domain.tld/server/execute and send Json object in payload like this {uri:"reset-password",old:"",new:""}.
at backend
use
app.all("/server/execute", function (req, res) {
try {
// decrypt payload
req.url = payload.uri;
next();
} catch (error) {
// error handling
var err = writeCustomError(error.message || error.errmsg || error.stack);
res.status(417).json(err).end();
}
});
app.all("/reset-password", function (req, res) {
try {
// reset logic
} catch (error) {
// error handling
var err = writeCustomError(error.message || error.errmsg || error.stack);
res.status(417).json(err).end();
}
});
so in this way only developer know where password reset logic and how it can called and what parameters are required.
I will also suggest you to create different router files for express like QueryRouter,InsertRouter etc.
Also try to implement end-to-end encryption.Any query regarding post,kindly comment it.

node express try catch not working as expected

I'm a beginner in Node/Express.js and I'm trying out some try catch logic but doesn't seem to work as expected.
app.get("/tasks/:id", async (req, res) => {
try {
const _id = req.params.id;
const task = await Task.findById(_id);
if (!task) {
return res.status(404).send("task not found");
}
res.send(task);
} catch (error) {
res.status(500).send("Internal server error");
}
});
from this code sample, I'm making a query to Mongo DB to fetch some task but the problem is that if the task is not found, instead of running through the if statement, the program jumps directly to the catch block hence the if condition is not checked thus resulting to a different error. How can I fix this issue?
This is simply how MongooseJS works - check their Promises documentation and you will see that if a document is not found, an error will be thrown. If you were not using await, the findById() documentation shows how an error is returned if it cannot be found:
// find adventure by id and execute
Adventure.findById(id, function (err, adventure) {});
You can simply modify your route to look like the following:
app.get("/tasks/:id", async (req, res) => {
let task;
try {
task = await Task.findById(req.params.id);
} catch (error) {
return res.status(404).send("task not found");
}
/* perform other checks or actions here if desired */
res.send(task);
});
This is a little more flexible if you want to perform other error-checking; task is declared first so it can be accessible outside the try/catch block, and a 404 error is thrown if the task does not exist.
You can also look at the exists method which will return true or false based on if the document exists, but since you need the actual result that does not make as much sense.
You don't indicate what Task is, but it appears that it is rejecting when it doesn't find anything, rather than returning a false value (which is what you seem to be expecting).
Given that, you should probably just handle the error that it is throwing with something like
} catch ( error ) {
// Will need to adapt this if to something that identifies the error thrown by `getById`
if ( error.message.includes( 'not found' ) ) {
res.status( 404 ).send( 'task not found' );
} else {
res.status( 500 ).send( 'Internal server error' );
}
}

Returning Error Values Through Axios/Express To React App

I've got a handleSubmit function that fetches data from my backend as part of a larger component. I'd like to send the error information to my redux store and/or local component when the back-end fails, but am unable to do so.
The handleSubmit function looks like this (it's using React hooks, which are wired up correctly. Can post the full component if that is useful):
const handleSubmit = async (e, { dataSource, filter, filterTarget }) => {
e.preventDefault();
setIsLoading(true);
setErrorValue(null);
setError(false);
const token = localStorage.JWT_TOKEN;
const link = filterTarget === "Identifier" ? `http://localhost:8081/api/${dataSource}/${filter}`: `http://localhost:8081/api/${dataSource}?filter=${filter}&filterTarget=${filterTarget}`;
try {
let data = await axios.get(link, { headers: { authorization: token }});
props.setData(data);
setError(false);
setIsLoading(false);
} catch (err){
setErrorValue(err.message);
setError(true);
setIsLoading(false);
};
};
I'm intentionally making bad requests through the form, which will trigger an error in my backend. These are handled through my custom Express middleware function, which looks like this (I'll add more once I get this framework to work):
handleOtherError: (error, req, res, next) => { // Final custom error handler, with no conditions. No need to call next() here.
console.log("This error handler is firing!");
return res.status(500).json({
message: error.message,
type: "ServerError"
});
}
I know that this function is firing because the console.log statement is appearing on my server, and if I change the status code, so does the status code error on the front-end in my Google Chrome console.
In fact, if I go to the network tab, the correct error information appears for my request. Here's the video of me making a bad request:
However, when I try to access the err.message on my front-end, I'm not able to do so. The err.message in my try/catch handler for the handleSubmit function only ever gives me the Request failed with status code XXX
What am I doing wrong?
See https://github.com/axios/axios#handling-errors
You can access the response by using err.response.data.message, not err.message.
Found the answer posted elsewhere: https://github.com/axios/axios/issues/960
Apparently, to get the message, you have to use err.response.data.message
Simply using "err" will only give you a basic string respresentation of the error.

How to replace error message with an error page

I currently have when something goes wrong i display error text but i would like to replace this with a presentable error page instead of just text and wanted a little more help on how to go about this.
This is currently my code for displaying error text:
return function (req, res, next) {
errorRepo.get(req.get('error'), serviceTokenHandler.makeToken(), function (err, errorInfo) {
if (err || !errorInfo) {
res.status(500).render('error', {
message: 'This is my error message'
});
} else {
.....
next();
}
});
};
What do i need to do to redirect to an error page instead of just showing a message? Should i replace the inside of the if block with a method call that would redirect to another page?
I assume you are using express for your application. If you want to render a beautiful error page, you would do that just as you would render any other page.
The only difference between an error page and a "normal" page is - simply put - the http status code which ranges above 400.
E.g. you'd do:
...
if (err || !errorInfo) {
res.render('error-page', function(err, html) {
res.status(500).send(html);
});
}
...
Assuming you are using Express 4.x.
You can create an error.html file which you want to render when error occurs.
<html><body>
ERROR
</body> </html>
In node render the error.html when error occurs:
if(error) {
res.sendFile('error.html', { root: path.join(__dirname, '../views');
}
This way you can keep the html and node code seperate.
Express 4.x documentation for referance http://expressjs.com/en/4x/api.html#res.sendFile

How to construct a non-custom error by Hand in Sails.js

I am writing a Service to be used by my Controllers in my Sails.js application.
If an error is thrown in the Service, I would like to return a error. I am used to the syntax of function callback(err, bar){ if (err) return error}. I am in a slightly different case, though. In the following code
function callBack(err, uploadedFiles){
if (err) return err;
if (uploadedFiles.length == {
return foo; //This is what needs to be of type "err"
}
});
}
}
So do I create a JSON object like
return { error: "error", message: 404}
I am not sure how to do this.
Why are you not using sails functions for responses? I am also new so excuse me if said something silly.
If you want to send a 404 status code which is for Not Found errors the you can use sails provided response res.notFound() like this:
return res.notFound({
message: "Some Message Here"
});
If you want to show completely custom message without any status code like 404 then use send() instead like this:
return res.send({
status: "404 or anything you like",
message: "Some Message Here"
});
Sorry, res.send() will also generate a status code but it will be 200 which means OK, so its a success code.
I believe it is:
{success:false, error: err}
You can raise your 404 error in your Services like this (assuming your service needs to work asynchronously):
var err = new Error('your message');
err.status = 404; // could be other HTTP status
return cb(err);
And in your calling function, you can handle the error like this:
SomeServices.somefunction(options, function (err, data) {
// res.negotiate(err) will automatically trigger res.notFound if err.status is 404
if (err) return res.negotiate(err);
/* your logic if not 404 */
}
The codes are quite simple here. Is that what you want?

Categories

Resources