I have some web-rest services in Spring and they accept a body. If a malicious user creates an incorrect body:
{
\"usuario": "blabla"
}
Spring handles the exception automatically by returning the error:
"code": "UNKNOWN_ERROR",
"message": "JSON parse error: Unexpected character ('\\' (code 92)): was expecting double-quote to start field name; nested exception is com.fasterxml.jackson.core.JsonParseException: Unexpected character ('\\' (code 92)): was expecting double-quote to start field name\n at [Source: java.io.PushbackInputStream@3fb5605c; line: 2, column: 4]",
"type": "T",
"component": "UNKNOWN_COMPONENT",
"application": "Mweb",
"timeStamp": "2022-02-18T13:15:39.224Z",
"errors": [{"code": "UNKNOWN_ERROR"}],
"stackTrace": [
{
"methodName": "readJavaType",
"fileName": "AbstractJackson2HttpMessageConverter.java",
"lineNumber": 240
},
{
"methodName": "read",
"fileName": "AbstractJackson2HttpMessageConverter.java",
"lineNumber": 225
},
{
"methodName": "readWithMessageConverters",
"fileName": "AbstractMessageConverterMethodArgumentResolver.java",
"lineNumber": 201
},
{
"methodName": "readWithMessageConverters",
"fileName": "RequestResponseBodyMethodProcessor.java",
"lineNumber": 150
},
{
"methodName": "resolveArgument",
"fileName": "RequestResponseBodyMethodProcessor.java",
"lineNumber": 128
}
]
}
Since the app fails before it reaches my controller, when it tries to create the input object, I need to return a "custom" message first.
I have read and tried to use:
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* Se captura el tipo de error.
* @param e objeto capturado
* @return salida del metodo.
*/
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<myException> handleException(Exception e){
return crearException(e,Constantes.INTERNAL_SERVER_CODE, Constantes.EXCEPTION_HANDLER_JSON);
}
/**
* Metodo auxiliar para crear el objeto del error
* @param e objeto capturado
* @return objeto del error.
*/
private ResponseEntity<myException> crearException()......
The problem is that it doesn't fit inside the method.
I have chosen the HttpMessageNotReadableException because in the Java console it is the first cause by that appears as an error.