I would like to keep all of error descriptions in a single .js file as a dictionary, so that I can display the appropriate description from the rest of my JavaScript web app. I am very new to JS web app development and I am wondering how to achieve this.
currently I have been trying this:
errorDesc.js:
var descriptions = {
errorCode00 : "description",
errorCode02 : "description",
errorCode03 : "description"
}
export function getResponseDescription(name) {
return descriptions[name];
}
main.js:
import {getResponseDescription} from "./errorDesc";
But in the console I get the following error:
Uncaught SyntaxError: Unexpected token {
I will suggest you have a file consist of error classes (used to set an error message and error name) which extend Error class and in the constructor assign the error message and error name to the object e.g.
class AuthorizationError extends Error {
constructor(message) {
super(message);
this.name = 'AuthorizationError';
this.message = message;
}
}
// classes of other error types
after that set, the status code based on the type of error and return e.g.
const errorHandler = (error, req, res, next) => {
const message = error.message || 'Something went wrong';
let status = null;
switch(error.name) {
case 'AuthorizationError':
status = 403;
break;
// other error types
}
res.status(status).json({ message });
}
wherever you encounter error create a new instance of the type of error class
next(new AuthorizationError('Username or password do not match'));
Related
If I use Throw new Error("User not found"), then it gives in response
{status:false,message:"User Not Found"}
But with status code 500, And I need Status 400 in Postman
custom Error using throw function
but if we use res.status(500).send({ status: false, message: "User not found" })
then it gives status code 400, And I need Status 400 in Postman . So, I need same status code in postman only.This is the problem. Tyler2P and Abin Bala , I followed your code but I am unable to get desired status code in postman status.
You can create a custom error class as below and throw it with appropriate message and httpCode. You can also add more properties. Then you can catch the custom error object using the catch block and get the required values.
class CustomError extends Error {
name;
httpCode;
message;
constructor(name,httpCode, message){
super(message);
this.name = name;
this.httpCode = httpCode;
this.message = message;
}
}
errorThrowingFunction.js:
//import the custom error class in the module that you //are going to use it.
errorThrowingFunction = () => {
const authToken = myCache.get("token");
if (!authToken) {
throw new CustomError('Error',401,'token missing');
} else {
return authToken;
}
}
index.js:
handler = () => {
try {
errorThrowingFunction();
} catch(error){
const response = {
statusCode: error.httpCode,
body: JSON.Stringify(error.message),
isBase64Encoded: false,
//add other headers
}
return response;
//if you are using this in rest service, the use below line
//return res.status(error.httpCode)send(response);
}
}
I am very new to typescrypt, and I'm currently in the process of migrating a project from JS to TS.
While I was changing some things on my server endpoints, an error appeared:
Property 'email' does not exist on type 'string | JwtPayload'
This is my code so far:
try {
const token = await TokenController.getTokenFromRequest(req);
const decoded = jwt.decode(token);
const user = await AuthController.getUserByMail(decoded.username); // <- Error appears here
res.json(user);
} catch (error: any) {
ErrorController.errorCallback(error, res);
}
Edit: My code for 'getUserByMail' looks like so:
static async getUserByMail(email: string, includePassword = false) {
let query = User.findOne({
email: email
});
if (!includePassword) {
query.select('-password');
}
return query.exec();
}
I know that the error happens because I'm trying to access a property that string doesn't have. Any suggestions?
Create global.d.ts:
// global.d.ts
declare module "jsonwebtoken" {
export interface JwtPayload {
//make optional so when you try to decode stuff other than user it will show it can be undefined
email?: string;
}
}
Following code generates exception as UserAlreadyExist.
Optional<User> userCheck = userRepository.findByUsername(createRequest.getUsername());
if(StringUtils.hasText(userCheck.get().getUsername())){
String errorMessage = "User already exist: "+ userCheck.get().getUsername();
throw new UserAlreadyExistException(errorMessage);
}
When i try to get error message from my react app with these codes i only get Internal server error message. My header contains header token and application/JSON header.
export const createUserService = (data) => {
return new Promise(((resolve, reject) => {
axios.post(USERS_BASE, data, getHeaderWithToken())
.then(function (response) {
resolve(response);
})
.catch(error=>{
console.log(error)//returns "Internal Server Error" message
console.log(error.response) // returns object with empty message field and other parameters.
reject(error)
})
}));
};
How can i get the error message i sent like
String errorMessage = "User already exist: "+ userCheck.get().getUsername();
throw new UserAlreadyExistException(errorMessage);
this is my UserAlreadyExistException class btw.
public class UserAlreadyExistException extends RuntimeException {
public UserAlreadyExistException(String message) {
super(message);
}}
You can return custom Response with #RestControllerAdvice for the custom exception you are throwing.
Please check the example below.
#RestControllerAdvice
public class ControllerExceptionHandler {
#ExceptionHandler(value = {UserAlreadyExistException.class})
#ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ErrorMessage userAlreadyExistException(UserAlreadyExistException ex, WebRequest request) {
ErrorMessage message = new ErrorMessage(
status,
date,
ex.getMessage(),
description);
return message;
}
}
It will be much easier for you to see the error in your Frontent application with a Response that you will return like this.
I have created an CRUD API using typescript NodeJS, Express and MongoDB. What I am trying to achieve is that when using the POST method when I send the correct parameter. API works fine. However whenever I send incorrect parameters to the API the whole NodeJS app crashes, I get an error message in console that the parameters passed to the API are wrong and I will have restart the application again.
When as user sends the incorrect parameters to the API. I don't want the NodeJS app to crash. I want to display the useful error message. Keep the app running. I Don't want to restart the application.
This is the code i use to create New providers.
public addProviders(req: Request, res: Response, next: NextFunction) {
var type = req.body.type,
name = req.body.name;
let newProvider = new Provider({
type,
name
})
newProvider.save()
.then((provider: Object) => {
if (provider) {
let statusCode = res.statusCode;
res.json({
statusCode,
provider
})
}
})
}
Below is the code that i have tried so far.
try {
newProvider.save()
.then((provider: Object) => {
if (provider) {
let statusCode = res.statusCode;
res.json({
statusCode,
provider
})
}
})
}
catch (e) {
res.json("enter valid parameters")
}
I am new to NodeJS. Thanks in advance.
You need to add input validation middleware to check inputs before adding to Database.
#1 You can check it manually, like:
var { type, name } = req.body;
if (typeof type !== 'string') {
res.status(400).send("type input is not valid");
} else if (typeof name !== 'string') {
res.status(400).send("name input is not valid");
} else {
let newProvider = new Provider({
type,
name
})
// ...rest of the code
}
#2 Or you can use a package like express-validator.
const HttpError = require("../models/http-error");
//http-error.js
class HttpError extends Error {
constructor(message, errorCode) {
super(message); // Add a "message" property
this.code = errorCode; // Adds a "code" property
}
}
module.exports = HttpError;
What is the differences betwen err and error what is the job over here err?
err is An optional identifier to hold an exception object for the associated catch-block. MDN try...cactch
const error is the object of your custom error handler