Error 0, logger 1.default) is not a function - javascript

This code was built to allow us to save errors to our database.
const logErrors = function (data) {
try {
let error = { date: new Date(), ...data };
databaseConnections[dbMappings['BACKEND_ERROR_DB_MAPPING']['default']].collection('BackendLogs').insert(error);
} catch (error) {
const slackLog = new Log();
slackLog.error(error.toString());
}
};
export default logErrors;
The code works OK and saves errors to our database, but it occasionally throws the error "0, logger 1.default) is not a function."
What could be the problem?
Example scenario
catch (error) {
// error.stack = error.stack + " " + JSON.stringify(this.data);
if (error) {
logErrors({ message: error }); <<<<<
}
}

Related

How to catch the Error message coming from Spring in react

I'm trying to catch the error this error message from my Rest controller in spring
#GetMapping
public List<Student> getAllStudent() {
throw new IllegalStateException("Opps can not get all students");
// return studentService.getAllStudents();
}
The error is catch in react this way, what I'm trying to do is to show in the console the Error message
import fetch from "unfetch";
const checkStatus = (response) => {
if (response.ok) {
return response;
} else {
let error = new Error(response.statusText);
error.response = response;
response.json().then((e) => {
error.error = e;
});
return Promise.reject(error);
}
};
export const getAllStudents = () =>
fetch("http://localhost:1020/api/students").then(checkStatus);
And then is consume by this method to show it in the console
const fetchAllStudents = () => {
this.setState({
isFetching: true,
});
getAllStudents()
.then((res) =>
res.json().then((students) => {
console.log(students);
this.setState({
students,
isFetching: false,
});
})
)
.catch((error) => {
console.log(error.error.message);
// const message =error.error.message;
// errorNotification(message,message)
this.setState({
isFetching: false,
});
});
};
The problem is that I get is that "message" is undefined I want to log "Opps can not get all students" in the console:
Add this line to your application.properties file:
server.error.include-message=always
And try throwing ResponseStatusException, so that you give a HTTP Status, together with the message, and not just 500 Server Error.
Like this:
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Your Message...");

Throwing errors using async/await in AWS Lambda node.js function

I am trying to throw an error to the calling function and the error is not getting captured. The exception is not propagating to the calling function.
'use strict';
const { Pool } = require('pg');
const pool = new Pool();
var result;
exports.handler = async (event) => {
var payload = event;
try{
result = await insertOrder(payload, 'test');
}
catch (err) {
console.error("Error from main: " + err);
throw err ;
}
return result;
};
async function insertOrder(payload, name)
{
const client = await pool.connect();
try{
const queryString = {
text: "INSERT INTO public.orders(payload, shop_name)" +
"VALUES ($1, $2) RETURNING id",
values: [payload, name],
};
const result = await client.query(queryString);
var orderId = result.rows[0].id;
}
catch (err) {
await client.query('ROLLBACK');
console.log("Error from child: " + err);
throw err;
}
finally {
client.release();
return orderId;
}
}
Here is what is written to the log:
INFO Error from child: error: INSERT has more target columns than expressions
The console.error in the calling function is not written to the log. What am I am missing? TIA!
Moving return orderId; to try block solved my issue

Propagate ApolloError to client

I have real hard time to get custom Apollo error on the client side.
Here is the server code:
...
const schema = makeExecutableSchema({
typeDefs: [constraintDirectiveTypeDefs, ...typeDefs],
resolvers,
schemaTransforms: [constraintDirective()],
});
const server = new ApolloServer({
schema,
dataSources,
context({ req }) {
const token = req.headers.authorization;
const user = token ? getUserFromToken(token) : '';
return { user };
},
debug: false,
formatError: (err) => {
// ToDo: Generate unique token and log error
if (err!.extensions!.code == 'INTERNAL_SERVER_ERROR') {
return new ApolloError('We are having some trouble', 'ERROR', {
token: 'uniquetoken',
});
}
return err;
},
uploads: false,
});
...
Client code:
...
const ADD_CLAIM = gql`
mutation addClaim($claim: ClaimInput!) {
addClaim(claim: $claim) {
id
}
}
`;
...
const [addClaim, { data, error }] = useMutation(ADD_CLAIM);
...
const onSubmit = async () => {
try {
debugger;
const r = await addClaim({
variables: {
input: {
id: insured.insured,
date: '20/12/2020',
...
therapy: treatment.treatments.map(treat => ({
id: treat.treatId,
...
})),
},
},
});
debugger;
console.log('r', r);
} catch (err) {
debugger;
setFormError(error ? error.message : err.message);
console.log('Error:', err);
}
};
...
if (error) {
debugger;
return <div>error</div>;
}
I expect to get the custom error : "We are having some trouble".
However, no matter what I do I got: "Response not successful: Received status code 400"
I am 100% give custom error from the server:
But I receive on client side:
Moreover, when I check network tab of Developer Tools, response I do have my error:
But I cannot access it from the code.
BTW, in the playground I see my error:
Here where are my errors :
error.networkError.result.errors
What nobody knows ?
Or
const errorLink = onError(({ graphQLErrors, networkError }) => {
debugger;
console.log(graphQLErrors);
console.log(networkError);
});
const client = new ApolloClient({
...
link: ApolloLink.from( [errorLink, ...]),
});
It works as well.
Yes, sometimes GraphQL is a nasty beast

Throw object instead of returning string

How to build an Error object instead of give its a string? https://codesandbox.io/s/pwr973487x
async function getUrl() {
try {
const res = await axios.get('https://httpstat.us/500')
} catch(e) {
const errorObj = {
status: 500,
message: 'Internal server error, something is not defined etc'
}
throw new Error('err') //how to build object?
}
}
I want throw Error() to return errorObj. Do I have to do my own class to do that or I can modify the existing Error class for that? I need that so it standardize my error message of my different set of Apis.
You can use the error object returned from catch
try {
const res = await axios.get('https://httpstat.us/500')
} catch(e) {
e.message = 'Internal server error, something is not defined etc';
throw e;
}
You can just add a field to the Error object, e.g.
var err = new Error('Internal Server error');
err.customField = { someProperty: 'some value'};
console.log(err);
And then you can throw it as normal:
throw err;
When you catch the error (higher up in the call stack) you can pull out the custom field:
try
{
throw err;
}
catch (e)
{
console.error(e);
console.log(e.customField);
}
With ES6 onwards you can also create your own error class:
class MyError extends Error {
constructor(message, customValue) {
super(message);
this.field = customValue;
}
get customField() {
return this.field;
}
set customField(obj) {
this.field = obj;
}
};
var ex = new MyError('Error message', {someProperty: 'some value'});
console.dir(ex);
console.log('My custom error details: ', ex.customField);
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('Failed in some way', {
cause: {status: 400}
});
} catch(e) {
console.log(e); // Error('Failed in some way')
console.log(e.cause) // {status: 400}
}
or throw the Error instance with the custom property
try {
const error = new Error('Failed in some way');
error.status = 400;
throw error;
} catch(e) {
console.log(e); // Error('Failed in some way')
console.log(e.status) // 400
}

neo4j cypher will not update database

following code gets error "result undefined" (last error trap) please help:
try {
var driver = neo4j.driver("bolt://localhost:7474", neo4j.auth.basic(userName, passWord));
} catch (err) {
alert(err.message);
}
const session = driver.session();
const personName = 'Alice';
try {
const resultPromise = session.run('CREATE (a:Person {name: $name}) RETURN a', {
name: personName
});
} catch (err) {
alert(err.message);
}
try {
resultPromise.then(
result => {
session.close();
const singleRecord = result.records[0];
const node = singleRecord.get(0);
console.log(node.properties.name);
driver.close();
}
);
} catch (err) {
alert(err.message);
}
I think the error is due to the fact that you are using the java bolt driver on the http port (7474) of Neo4j.
Just change the connection url by this one : neo4j.driver("bolt://localhost:7687", neo4j.auth.basic(userName, passWord))

Categories