Error Handling / Throw error in Strapi 4.0 - strapi

in Strapi 4.0, i want to validate the input before saving. So i created lifecycles.js file as per the documentation and added the code:
module.exports = {
beforeCreate(event) {
//validation login here;
if (!valid) {
throw strapi.errors.badRequest('Invalid Entry');
}
},
}
How ever throw strapi.errors.badRequest('Invalid Entry'); is giving an error :
Cannot read property 'badRequest' of undefined
My guess is the Strapi v4 changed it from version 3. I looked everywhere but couldn't find a solution.
Any idea on how to handle error in lifecycles.js?

I had a similar situation with a forbidden error. I got to do it importing a class from #strapi/utils/lib/errors.js
const { ForbiddenError } = require("#strapi/utils").errors;
...
if (!authorized) {
throw new ForbiddenError(errorMessage);
}

You can show the list of errors based on your requirement
const { ValidationError } = require("#strapi/utils").errors;
...
if (formValidationError) {
throw new ForbiddenError("Fill the form");
}
Strapi comes with a lot of error response functions here are they
HttpError,
ApplicationError,
ValidationError,
YupValidationError,
PaginationError,
NotFoundError,
ForbiddenError,
PayloadTooLargeError,
UnauthorizedError,
PolicyError,

Related

How to Only Catch non-ApolloError Errors with Apollo GraphQL Server

I have an Apollo GraphQL server, where I want to only report internal server errors (not errors extending ApolloError like AuthenticationError, UserInputError, etc.).
Here is the plugin that I wrote that catches internal server errors and reports them:
const errorReportingPlugin = {
requestDidStart(_) {
return {
didEncounterErrors(ctx) {
// If we couldn't parse the operation, don't do anything
if (!ctx.operation) return
for (const err of ctx.errors) {
// Don't report errors extending ApolloError like AuthenticationError, UserInputError, etc.
if (err instanceof ApolloError) {
continue
}
// report error here...
}
}
}
}
}
However err instanceof ApolloError returns false when I throw AuthenticationError, which extends ApolloError.
So I tried to check the class of the err by printing the constructor name and I got GraphQLError.
console.log(err.constructor.name)
Does anyone know how to avoid reporting all errors extending ApolloError?
The solution is to check whether err.originalError (not err) is an instance of ApolloError like this:
if (err.originalError instanceof ApolloError) {
// don't report error since it is a user facing error like AuthenticationError, UserInputError, etc.
}
credit to #xadm

How to unit test graphql query/mutation error with Mocha and Chai?

Since graphql error is not an standard Error. It's a GraphQLError
I can't figure out how to write unit test when graphql query/mutation throw an exception.
Here is my try:
it('should throw an error when lack of "id" argument for user query', async () => {
const body = {
query: `
query user{
user {
id
name
}
}
`
};
try {
const actualValue = await rp(body);
} catch (err) {
logger.error(err);
}
// logger.info(actualValue);
expect(1).to.be.equal(1);
// expect(actualValue).to.throw()
});
I found some tests in graphql.js repo. https://github.com/graphql/graphql-js/blob/master/src/tests/starWarsQuery-test.js#L393
But I think the way they test the query/mutation error is not correct.
They just do a deep equal with the error. But before running the test suites, how do I know the error data structure like locations: [{ line: 5, column: 13 }],? Maybe I should use snapshot testing so that I don't need to know the error data structure?
Check this package https://github.com/EasyGraphQL/easygraphql-tester there is an example with mocha and chai on the documentation

cannot find the datastore during the compiling in Angular2

When I try to run my page in Wakanda studio 1.1.3, I am getting an error during the compiling when converting the TS to JS. It shows me an error stating "cannot find the datastore"; which is present in my wakanda database. Is anyone else getting the same error?
here is the code:
this.wakanda.catalog.then(ds=>{
ds.TestDatabase.testmethod().then(op=>{
console.log(op);
});
});
my wakanda.service.ts is of the following
import {WakandaClient} from 'wakanda-client/browser/no-promise';
export class Wakanda {
private _client: WakandaClient;
private _catalog;
constructor() {
//this._client = new WakandaClient({ host: 'http://127.0.0.1:8081' });
this._client = new WakandaClient({});
this._catalog = null;
}
get catalog() {
if (!this._catalog) {
return this._client.getCatalog().then(c => {
this._catalog = c;
return c;
});
}
return Promise.resolve(this._catalog);
}
get directory() {
return this._client.directory;
}
get wakandaClientVersion() {
return this._client.version();
}
}
where TestDatavase is a table in my datastore and has a method called testmethod.
[default]
/Users/adithyavinayak/Documents/Wakanda/solutions/TestDatabase/TestDatabase/web/src/app/home/home.component.ts:21:8
Property 'TestDatabase' does not exist on type 'Catalog'. [default]
Checking finished with 4 errors
This one happens even if i make a call to any datastore during compile time.
The solution for this problem is by using the return type of the catalog to any
this.wakanda.catalog.then((ds:any)=>{
ds.TestDatabase.testmethod().then(op=>{
console.log(op);
});
});
This one works without any problem during the time of compilation.

Realm throw catch swift 2.0

does anyone know the syntax for the try-catch of the following realm function is?
realm.write() {
realm.add(whatever)
}
I'm getting the following error:
call can throw but it is not marked with 'try' and the error is not
handled
From what I imagine realm.write() can throw an exception. In Swift 2 you handle exceptions with do/catch and try.
I suspect that you should do something like this:
do {
try realm.write() {
realm.add(whatever)
}
} catch {
print("Something went wrong!")
}
If realm.write() throws an exception, print statement will be invoked immediately.
It looks like an NSError gets thrown. See the Swift 2.0 source
Adding on to #tgebarowski's answer:
do {
try self.realm.write {
realm.add(whatever)
}
} catch let error as NSError {
print("Something went wrong!")
// use the error object such as error.localizedDescription
}
You can also try
try! realm.write {
realm.add(whatever)
}

Gets FormatException when trying to query data to Parse.com in Unity

I'm using Parse plugin 1.5.5 for Unity 5.1.3 in order to communicate with Parse.com in Unity. I'm getting FormatException when trying to connect to Parse when there is no internet connection with following code. I was wondering if this is a bug of Parse plugin or anything I did wrong.
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Data");
query.FirstAsync().ContinueWith (task =>
{
if (task.IsCanceled)
{
Debug.Log ("parse canceled");
}
else if(task.IsFaulted)
{
Debug.Log ("parse error");
}
else
{
Debug.Log ("parse retrieved");
}
});
Error code is following.
FormatException: Input string was not in the correct format
System.Int32.Parse (System.String s) (at /Users/builduser/buildslave/mono- runtime-and-classlibs/build/mcs/class/corlib/System/Int32.cs:629)
Parse.PlatformHooks+HttpRequestUnity.getStatusCode (UnityEngine.WWW www)
Parse.PlatformHooks+HttpRequestUnity+<>c__DisplayClass40+<>c__DisplayClass46.<ExecuteAsync>b__3a (UnityEngine.WWW www)
Parse.PlatformHooks+<>c__DisplayClass24.<RegisterNetworkRequest>b__23 ()
Parse.PlatformHooks+<RunDispatcher>d__2e.MoveNext ()
UnityEngine.Debug:LogException(Exception)
Parse.<RunDispatcher>d__2e:MoveNext()
Thank you,

Resources