Create Custom exception with symfony fos rest - fosrestbundle

{
error: {
code: 500,
message: "No route found for "GET /api/v1/adf""
}
}
this is the default exception, how can I create a different view? I tried with exception wrapper but it is not working.

Related

Is there a way to have Nest use the ExceptionsHandler error message as the API response message when an exception is thrown?

When an error is thrown within my Nest API, often times the error that is thrown is not an HttpException, and therefore the standard Nest API response that I see from the client's side is:
{
"statusCode": 500,
"message": "Internal server error"
}
But when I look at the console log, there is a much more descriptive error message, for example:
[Nest] 18476 - 06/23/2022, 2:28:07 PM ERROR [ExceptionsHandler] Cannot perform update query
because update values are not defined.
UpdateValuesMissingError: Cannot perform update query because update values are not defined.
Is there a way I can route this message to be the in the response body of the response given back to the API client?
You can use Global Filter in NestJs to catch error and then throw a good error.
For exemple, you can create a Exception Filter
// UpdateValuesMissingError.exception-filter.ts
import { ArgumentsHost, Catch, ExceptionFilter } from '#nestjs/common';
import { Request, Response } from 'express';
#Catch(UpdateValuesMissingError)
export class UpdateValuesMissingErrorFilter implements ExceptionFilter {
catch(exception: UpdateValuesMissingError, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
console.log(exception);
response.status(400).json({
statusCode: 400,
timestamp: new Date().toISOString(),
path: request.url,
});
}
}
and in your main.ts add this
app.useGlobalFilters(new HttpExceptionFilter());
And now in response.status(400).json({}) you can add everything you want in your body. Like the error message of Axios.

How do i handle HTTP load failed (error code: -1009 [1:50]) in swift 4?

I created on app using swift 4 and Xcode 9. when I login into my app I send a request and successful login on result which come from json. But when I switch my internet of my phone it crashed and give me this error
HTTP load failed (error code: -1009 [1:50])
So how do I handle this error and give popup or any warning to user to check your internet connection without app crashing.
Swift 4, Xcode 10.1
You can access to the error code:
class ViewController1: UIViewController, URLSessionDataDelegate {
...
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if error != nil {
debugPrint("error message: \(error!)")
debugPrint("code: \(error!._code)")
if error!._code == -1009 {
...
}
}
}
}
See also source code at: https://stackoverflow.com/a/53402801/966789

Problems with bootstrap autocomplete plugin

Use this plugin: https://github.com/nicolasbize/magicsuggest
I'm trying load json file, but have some troubles with it.
If I try such construction :
$('#').magicSuggest({
data: 'cities.json',
ajaxConfig: {
xhrFields: {
withCredentials: true
}
}
});
get an error:
POST http://...../cities.json 405 (Method Not Allowed)
Uncaught Could not reach server
When i'm change:
ajaxConfig: { method: 'GET' }
and try to put some letters into input field got such error:
Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
How can I fix this?

ValidationException errors in errors

In grails 2.3, I want to send customized error message by JSON. But when I use
class ApiError {
String message
String status
Exception error
}
and try to parse it as JSON I get: (I ommit irrevelant message and status)
"error": {
"cause": null
"class": "grails.validation.ValidationException"
"errors": {
"errors": [1]
0: {
"object": "com.example.Firm"
"field": "context"
"rejected-value": null
"message": "Property [context] of class [class com.example.Firm] cannot be null"
}
}
"localizedMessage": "Firm is not valid: - Field error in object 'com.example.Firm' on field 'context': rejected value [null]; codes [com.example.Firm.context.nullable.error.com.example.Firm.context,com.example.Firm.context.nullable.error.context,com.example.Firm.context.nullable.error.java.lang.String,com.example.Firm.context.nullable.error,firm.context.nullable.error.com.example.Firm.context,firm.context.nullable.error.context,firm.context.nullable.error.java.lang.String,firm.context.nullable.error,com.example.Firm.context.nullable.com.example.Firm.context,com.example.Firm.context.nullable.context,com.example.Firm.context.nullable.java.lang.String,com.example.Firm.context.nullable,firm.context.nullable.com.example.Firm.context,firm.context.nullable.context,firm.context.nullable.java.lang.String,firm.context.nullable,nullable.com.example.Firm.context,nullable.context,nullable.java.lang.String,nullable]; arguments [context,class com.example.Firm]; default message [Property [{0}] of class [{1}] cannot be null] "
"message": "firm is not valid: - Field error in object 'com.example.Firm' on field 'context': rejected value [null]; codes [com.example.Firm.context.nullable.error.com.example.Firm.context,com.example.Firm.context.nullable.error.context,com.example.Firm.context.nullable.error.java.lang.String,com.example.Firm.context.nullable.error,firm.context.nullable.error.com.example.Firm.context,firm.context.nullable.error.context,firm.context.nullable.error.java.lang.String,firm.context.nullable.error,com.example.Firm.context.nullable.com.example.Firm.context,com.example.Firm.context.nullable.context,com.example.Firm.context.nullable.java.lang.String,com.example.Firm.context.nullable,firm.context.nullable.com.example.Firm.context,firm.context.nullable.context,firm.context.nullable.java.lang.String,firm.context.nullable,nullable.com.example.Firm.context,nullable.context,nullable.java.lang.String,nullable]; arguments [context,class com.example.Firm]; default message [Property [{0}] of class [{1}] cannot be null] "
"stackTrace": [...143]
"suppressed": [0]
}
I do not understand; what's the point of using errors array in errors? And how to get only one errors array?
Here is a source code of this class.
Grails validation errors contain both global errors and field errors. Whenever validation exception occurs in grails, it doesn't throw a new exception for each field error, rather it wraps all field errors inside a single Error object. There may be global object errors, a global reason for rejecting an object.
So if you want to avoid errors inside errors then you should modify your ApiError class by replacing Exception error with List<Errors> errors and setting its value from instance.errors.
Or you can use a custom method to parse errors:
CodecLookup codecLookup
protected List retrieveErrors(instance) {
CodecLookup codec = Holders.applicationContext.getBean(CodecLookup)
List errors = []
g.eachError([bean: instance], {
error ->
errors.add(codec.lookupDecoder('HTML').decode(g.message(error: error)))
})
return errors
}
g is the namespace for ValidationTagLib that is available in each controller.

How do I catch a Constraint(Index) Violation in Grails?

Can't seem to find the right way to catch a MySQL index violation in a Grails app. Code from the controller:
try {
configurationInstance.save(flush: true) {
request.withFormat {...}
}
catch (JDBCException exception) {
flash.error = "This would be a duplicate attribute, please change the suffix."
render view: 'edit', model: [exception: exception]
}
When I provoke the error condition by submitting a duplicate value, the catch block is ignored and I get a 500 error page with these details:
URI /itools/configuration/save
Class com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException
Message Duplicate entry '1009303-photo-recommendable-exclusion-pattern.2-0' for key 'publisher_config_uk'
And in the console I've got:
ERROR errors.GrailsExceptionResolver - MySQLIntegrityConstraintViolationException occurred when processing request: [POST] /itools/configuration/save - parameters:
I've tried to catch
JDBCException
SQLError
SQLException
SQLDataException
SQLIntegrityConstraintViolationException
MySQLIntegrityConstraintViolationException
com.mysql.jdbc.exceptions.jdbc4.MySQLDataException
all to no avail. (FWIW I also applied a unique constraint on the attribute in question and it does nothing when it should cause a validation error. That's a completely different issue.)
What's the right way to do this?
Found it: it's DuplicateKeyException.
(I had to catch the generic Exception and see it's details to find this.)
Now I've got a new problem: upon trying to render or redirect I get "null id in itools.Configuration entry (don't flush the Session after an exception occurs)." This makes no sense to me -- the new entity was never saved to the DB because of the duplicate key, so why would a null ID object be a problem?