nestjs-i18n in DTO validation just throw bad request error - internationalization

im using nestjs-i18n in my dto and it just throw bad request error instead of my error messsage.
this is my dto:
export class SignUpDto{
#ApiProperty()
#MinLength(5, {
message: i18nValidationMessage('i18n.MIN', {message: 'err'})
})
username:string;
}
and i18n.json file:
{
"MIN": "You need to write at least 5 letter"
}
but this is the error in swagger:
{
"statusCode": 400,
"message": "Bad Request"
}
what is the problem?

Related

Is possible to populate GraphQL error response manually?

due to well-known N+1 problem we decided to move away from #ResolveField() feature of NestJS and use our implementation of DataLoader instead. By doing so, we must handle errors of resolvers manually because the resolution of graphql data is not driven by NestJS (or apollo) anymore.
This put us into a problem when we want to return a GraphQL error response (e.g. "Book not found") from graphql query in a standard manner like this:
{
"data": {
user: {
id: 1
book: null
}
}
"errors": [
{
"message": "Book not found",
"statusCode": 400
}
]
}
But since we are not using #ResolveField() anymore we resolve nested data (book) manually
we receive this response:
{
"data": null
"errors": [
{
"message": "Book not found",
"statusCode": 400
}
]
}
Is there any way to populate GraphQL error response manually?
#Query(() => User)
async user(#Args('id') id: number): Promise<User> {
const user = await this.userService.findOne(id);
try{
const book = await this.bookService.findOne(user.bookId);
user.book = book;
} catch (e) {
// How to populate GraphQL error response manually?
user.book = null;
}
return user;
}
Thanks for your help and have a nice day!

How to match objects in an array in no particular order in JsonPath?

I am working with Spring and MockMvc. I'm writing a unit test for a specific controller response. It looks something like this:
{
"errors": [
{
"error": "Bean validation failed.",
"message": "Bean: UserRegistrationDto. Class/field: userRegistrationDto. Constraint: SafePseudonym."
},
{
"error": "Bean validation failed.",
"message": "Bean: UserRegistrationDto. Class/field: addressLine1. Constraint: NotNull."
}
]
}
There is no guarantee of the order of the array errors. This is partly because of Spring's SmartValidator. I would like to check if both objects are in the the array, regardless of order.
Here is my code now:
mvc.perform(post("/registration")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(validExampleUserRegistrationDtoBuilder().addressLine1(null).pseudonym("oyasuna").build())))
.andDo(result -> System.out.println(result.getResponse().getContentAsString()))
.andExpect(status().isBadRequest())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.errors.length()").value(2))
.andExpectAll(
jsonPath("$.errors[0].error").value("Bean validation failed."),
jsonPath("$.errors[0].message").value("Bean: UserRegistrationDto. Class/field: addressLine1. Constraint: NotNull.")
)
.andExpectAll(
jsonPath("$.errors[1].error").value("Bean validation failed."),
jsonPath("$.errors[1].message").value("Bean: UserRegistrationDto. Class/field: userRegistrationDto. Constraint: SafePseudonym.")
);
Use containsInAnyOrder to verify (use your required json path)
andExpect(jsonPath("$
.message", containsInAnyOrder("1-st expected message", "2-nd expected message")))
.andExpect(jsonPath("$
.error", containsInAnyOrder("1-st expected error, "2-nd expected error")))

Golang GMAIL API 400: Invalid label:

Using Gmail API to read my mailbox. The message reading process is working as expected but I want to change the label of reading messages just for acknowledgment purposes so that I can have track of the reading messages list in my Gmail inbox only. Tried given two methods to change the label but non of them worked for me. Need suggestion on the same
Methods:
Codebase is written in Golang (as a backend)
Tried with Google API Explorer
(METHOD 1) -
Go sample code:
gmsg: = gmail.ModifyMessageRequest {
RemoveLabelIds: [] string {
"INBOX". //system defined label
},
AddLabelIds: [] string {
"INBOXING" //my custom label. created through Gmail
},
}
_, errDelete: = gService.Users.Messages.Modify("me", messageid, &gmsg).Do()
if (errDelete != nil) {
logs.Error("GMAIL SERVICE ERROR:: for [", accountEmail, "] while moving message to [INBOXING] folder ", errDelete.Error())
}
Got below error :
{"level":"error","msg":"GMAIL SERVICE ERROR:: for [sample#gmail.com] while moving message to [INBOXING] folder googleapi: Error 400: Invalid label: INBOXING, invalidArgument","time":"2021-08-09 20:05:13"}
(METHOD 1) -
Gmail Modify API
Payload
{
"addLabelIds": [
"INBOXING"
],
"removeLabelIds": [
"INBOX"
]
}
Response from Google API -
{
"error": {
"code": 400,
"message": "Invalid label: INBOXING",
"errors": [
{
"message": "Invalid label: INBOXING",
"domain": "global",
"reason": "invalidArgument"
}
],
"status": "INVALID_ARGUMENT"
}
}
Observation - *
On modifying message with custom label's Gmail API return's 400 bad
request, but if we request with system labels it allows us to modify
the label.
You are using the label name instead of label id. To obtain the label id, you have to use the Method: users.labels.list
Response:
Once you have the ID, you can now use it in Method: users.messages.modify
Request body:
Response:

How I can return my custom json file instead of default json file that generates spring boot?

I have a rest controller for authorization:
#RestController
class AuthController {
#PostMapping("/sign-up")
fun signUp(#RequestBody signUpRequest: SignUpRequest): ResponseEntity<String> {
some code here..
}
}
The signUp method gets SignUpRequest model as a request body. SignUpRequest model is:
enum class Role {
#JsonProperty("Student")
STUDENT,
#JsonProperty("Tutor")
TUTOR
}
data class SignUpRequest(
val role: Role,
val email: String,
val password: String
)
When I make /sign-up post request with JSON:
{
"role": "asdf",
"email": "",
"password": ""
}
It returns me an answer that were generated by spring boot:
{
"timestamp": "2020-02-12T05:45:42.387+0000",
"status": 400,
"error": "Bad Request",
"message": "JSON parse error: Cannot deserialize value of type `foo.bar.xyz.model.Role` from String \"asdf\": not one of the values accepted for Enum class: [Student, Tutor]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `foo.bar.xyz.model.Role` from String \"asdf\": not one of the values accepted for Enum class: [Student, Tutor]\n at [Source: (PushbackInputStream); line: 3, column: 10] (through reference chain: foo.bar.xyz.model.SignUpRequest[\"role\"])",
"path": "/sign-up"
}
Question is: How I can return my custom JSON instead of that default generated JSON?
I want to return my custom JSON, like:
{
"result": "Invalid user data are given",
"errors": [
{
"fieldName": "ROLE",
"text": "Given role does not exist"
},
{
"fieldName": "EMAIL",
"text": "EMAIL is empty"
}
]
}
I suggest you to create ErrorContrller that generates custom json map as response. Then when you will catch an error in sign-up method, call ErrorContrllers method.
You can find info from this link
Finally I found out a solution. You should create a class that annotates #ControllerAdvice, and make a method that annotates #ExceptionHandler.
#ControllerAdvice
class HttpMessageNotReadableExceptionController {
#ExceptionHandler(HttpMessageNotReadableException::class)
#ResponseBody
#ResponseStatus(HttpStatus.BAD_REQUEST)
fun handleException(
exception: HttpMessageNotReadableException
): PostSignUpResponseError {
val errors = mutableListOf<PostSignUpResponseErrorItem>()
errors.add(
PostSignUpResponseErrorItem(
fieldNamePost = "Role",
text = "Given role does not exist"
)
)
return PostSignUpResponseError(
result = "Invalid user data are given",
errors = errors
)
}
}
where PostSignUpResponseErrorItem and PostSignUpResponseError are:
data class PostSignUpResponseError(
val result: String,
val errors: List<PostSignUpResponseErrorItem>
)
class PostSignUpResponseErrorItem(
val fieldNamePost: PostSignUpRequestFieldName,
val text: String
)
Anyway, I still don't know how to attach this thing to a certain PostMapping method.

Swagger validation for request parameter and custom error message

I need a help regarding swagger validation with spring boot.
In Req1 it is not showing the field name, could you help with this? Also how to give custom error message for any validations?
Update:
In the response of the req1 is not showing field name(productCode) in message but in response of req2 we could see the field name.
type: object
description: get details request object
required: [productCode]
properties:
productCode:
type: string
minLength: 1
description: Identifier for application
--Req1-----
{
"productCode":""
}
--Res1-----
{
"code": "400",
"status": 400,
"message": "Validation Failed: string \"\" is too short (length: 0, required minimum: 1)"
}
--Req2-----
{ }
--Res2-----
{
"code": "400",
"status": 400,
"message": "Validation Failed: object has missing required properties ([\"productCode\"])"
}

Resources