score:25
the constructor for an error
object expects a string, not an object (which is why your scheme doesn't work).
you are free to add your own custom properties to the error object after you create it.
let err = new error('email already exists');
err.status = 400;
err.whateverelse = somevalue;
throw err;
the standard properties on an error object are (for some reason i don't know) not enumerable so they don't show up in some contexts (even though they are there). any new properties you add with plain assignment like above, will be enumerable.
fyi, you do this in multiple places, you can also subclass the error
object and give your subclass a constructor that takes whatever arguments you want to give it. that constructor can then call super(msg)
and then add its own properties to the error object from the constructor arguments.
the [object object]
is your message is because you are attempting to convert your error object to a string and the default string representation of the object is [object object]
. that will happen if you trying to use your error object in a string such as:
console.log('error: ' + err);
instead, you should pass the whole object to console.log()
like this:
console.log('error:', err);
and, the console.log()
gets the whole object and can display its properties.
you can also make your own error subclass that then takes whatever constructor arguments you want. so, if you want to pass an object to your custom error object, you can do that like this:
class myerror extends error {
constructor(data) {
super(data.message);
this.status = data.status;
}
}
throw new myerror({ status: 400, message: 'email already exists' });
score:0
you could try with the cause
propoty of :
ts has inaccurate value type about it at present, this is being discussed on the official to revolve it.
try {
throw new error('email already exists', {
cause: { status: 400 }
});
} catch(e) {
console.log(e); // error('email already exists')
console.log(e.cause) // { status: 400 }
}
or throw the error instance with the custom property
try {
const error = new error('email already exists');
error.status = 400;
throw error;
} catch(e) {
console.log(e); // error('email already exists')
console.log(e.status) // 400
}
score:1
https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/error
the error object takes a string parameter as the first parameter.
json.stringify the object if you are looking to print it out to the console.
throw new error(json.stringify({ status: 400, error: 'email already exists' }));
you will get something like this: uncaught error: {"status":400,"error":"email already exists"}
https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/json/stringify
Source: stackoverflow.com
Related Query
- Pass an object with JS throw new Error in node
- Why do I get an authentication error when I pass an axios config object with an authorization token? MERN
- How to test throw new error in redux-saga with Jest
- Object is not extensible error when creating new attribute for array of objects
- Error when creating new object from existing one using `...`: In this environment the sources for assign MUST be an object
- Why does react hook throw the act error when used with fetch api?
- 'Unauthorized' error when using AWS amplify with grahql to create a new user
- Get axios Response object when error occurred with Redux Saga
- Styled-components with npm link results in the error: "Trying to insert a new style tag, but the given Node is unmounted"
- Create new object with relation in Parse with React Native
- React router - pass api data to the linked component to open with a new page
- Slate.js throws an error when inserting a new node at selected region
- how to pass 'auth' or 'profile' object to firestoreConnect() with react-redux-firebase?
- react node passing file through axios with multer error 500
- ReactJS: replacing object from array with new value replaces whole array
- Unexpected node type error SequenceExpression with jest
- error "Converting circular structure to JSON -> starting at object with constructor 'FiberNode'" in react native
- Jest error with not transpiled node module
- Abstract type Node must resolve to an Object type at runtime for field Root.node with value \"\",received \"null\"."
- React DnD with HOC draggable elements throw Cannot set property 'props' of undefined error
- Throw error after the retry fails with Angular http.get
- I have an error with my jsconfig.json in react js says throw err Unexpected token } in JSON at position
- I have created a simple node server with CORS enabled. But when I do node server.js, it's throwing error
- throw an error with a statusCode inside NextJs to test the customized error page
- Getting referrence error while creating new array of object from existing array of objects?
- Arrow functions in class throw error with webpack-encore
- With NextJS Link, How to pass object clientside?
- How to pass object with history.push in react-router v5?
- Cannot add property key, object is not extensible error Apollo Client with antd
- I have been trying to create a new react project with npx create-react-app, but I am getting an error
More Query from same tag
- redux-persist got error: Store does not have a valid reducer
- conditional rendering with two values
- Can't access redux state object's key in TypeScript
- How to reconnect SignalR if its closed using react .Net core ( SQL dependency)?
- ReactJS: routing configuration issue
- Dynamically update the count for number of records available in react-table
- Why does my Get request sometimes work, but most of the time 404?
- how to update material ui textfield correctly onChange and put value into Json object?
- Classless react states?
- React Hooks: useState with onClick only updating after the 2nd time button is clicked?
- JS Regex for first letters only, but if the word it only two letters keep both AND numbers as is
- Storing and calling functions in React Context leads to weird behavior
- add touch event for iconElementLeft of AppBar - material-ui
- React and Ag-Grid: populating selectcelleditor through fetch gives 'state' of undefined
- Filtering Todos with seletion tag and checkbox
- Race condition when combining async action and accessing local state
- React Router 4 Optional parameter with custom path
- Need to create a common function for axios .then and catch
- React: Rendering Extra Components in Array Map
- input filtering in reactjs
- error: Do not use Array index in keys
- How to customize bootstrap 4 in reactjs app with reactstrap dependency?
- How to pass a html tag in the value of select input in React js?
- Highcharts chart with error bars using react-highcharts
- How to make sure the file input is video not anything else in Ajax
- React: import csv file and parse
- YARN warning "has unmet peer dependency". What do with this?
- How do I implement Express.js with a React app that was made using npm create-react-app since I won't be able to use app.listen?
- Is there any way to implement server-side caching using Apollo-server 2.x?
- Moment.js | not displaying with intended date format