How to log 415 errors in Spring - spring

My service is currently experiencing 415 errors, but I'm not getting any logs to find out what errors they are.
Will I be able to add logging in some kind of filter so that I can know what's going on?
#RequiresHttps
#RequestMapping(value = "/test", method = RequestMethod.POST)
public ResponseEntity<String> doAction(#NonNull #RequestBody CustomRequest[] requests) {

It looks like the 415 is happening inside spring mvc engine and it doesn't event reach your controller so that you can't really place the logs in our code (in doAction method for example).
Try to enable tomcat embedded access logs and you'll see the file with all the requests and return status. These are disabled by default so you should add the following into application.properties or yaml:
server.tomcat.accesslog.enabled=true
There are some configurations / customizations you can do with that, you can read about them in this tutorial for example

Related

Spring-Boot removes message from ErrorAttributes in response

When throwing an exception from a spring-boot controller, the message in the server response is empty - but only if I don't run locally. That last part is what's confusing me the most. I mean, it would make perfect sense to be able to have spring-boot remove parts from the error response. Like the stacktrace for example, noone wants to send that out except when debugging.
But when I run the application locally, I get the full error response, message, stacktrace and all (even when not running in debug mode, which I first suspected might be the reason for this). A typical error might look something like this:
{
"timestamp": "2020-10-14T09:46:35.784+00:00",
"status": 400,
"error": "Bad Request",
"trace": "webcam.yellow.service.controller.error.BadRequestException: New password must be different from old password! at /*REDACTED*/",
"message": "New password must be different from old password!",
"path": "/users/9"
}
But when I produce the same error on a deployed server, all I get is this:
{
"timestamp": "2020-10-14T09:29:57.720+00:00",
"status": 400,
"error": "Bad Request",
"message": "",
"path": "/users/9"
}
I don't mind the stacktrace being removed at all (in fact I want it to be removed), but I would really like to receive that error message.
One thought I had was that it might be related to cross-origin access, but I get the same behaviour when producing the error through swagger instead of our frontend, and swagger is same-origin.
I would fully expect such behaviour to be configurable in spring-boot, that would be convenient. Trouble is, I'm not configuring it. I compared the configuration properties of the running server to my local ones and I don't see any property that might be responsible for that. Nor can I find any if I google it. According to all the tutorials I find, this should work just fine. Which it kind of does, except not on the running servers.
Does anybody know what in spring-boot is causing this behaviour and how to configure it? Using spring-boot 2.3.3 by the way.
Additional information:
After some fooling around, I managed to reproduce the problem locally. I get the shortened error response if I build the application, and then run it from the command line directly with java -jar. Running gradle bootRun results in the server returning the full error message.
I've tried to return my own error response through a ControllerAdvice:
#ControllerAdvice
class BadRequestHandler : ResponseEntityExceptionHandler() {
#ExceptionHandler(value = [BadRequestException::class])
protected fun handleBadRequest(ex: BadRequestException, request: WebRequest): ResponseEntity<Any> {
val message = ex.message
return ResponseEntity(message, HttpHeaders(), HttpStatus.BAD_REQUEST)
}
}
This was just intended to be a quick test to see if I could change the server response. Turns out I can't, the client still gets the same response, although the handler is executed. So whatever takes the information out of the request must come further down the chain.
Does anybody have any idea what's happening here??
This is intended behavior since Spring Boot 2.3 as explained here
Setting server.error.include-message=always in the application.properties resolves this issue.
The response can be configured by injecting a custom ErrorController, like for example this one:
#Controller
class ExampleErrorController(private val errorAttributes: ErrorAttributes) : ErrorController {
private val mapper = ObjectMapper()
#RequestMapping("/error")
#ResponseBody
fun handleError(request: HttpServletRequest): String {
val webRequest = ServletWebRequest(request)
val error = errorAttributes.getError(ServletWebRequest(request))
// if it's not a 500, include the error message in the response. If it's a 500, better not...
val errorAttributeOptions = if (error !is HttpServerErrorException.InternalServerError) {
ErrorAttributeOptions.defaults().including(ErrorAttributeOptions.Include.MESSAGE)
} else ErrorAttributeOptions.defaults()
val errorDetails = errorAttributes.getErrorAttributes(
webRequest, errorAttributeOptions)
return mapper.writeValueAsString(errorDetails)
}
override fun getErrorPath(): String = "/error"
}
Note that this takes ErrorAttributeOptions.defaults() as a baseline, then configures what goes in. It appears that this default object is the one used by the default ErrorController spring boot provides, and it is in fact this object that is different depending on whether I run this from gradle/intelij directly or build it into a jar. Why I couldn't find out, but I verified and confirmed the behaviour. I assume it is intended, albeit not widely documented.
Once I learned this, I wondered why it wasn't possible to just configure the default Options object globally for an application rather than providing an entire controller, which in many instances would be sufficient, but it does not look like that's possible at this point.

Spring MVC GET Request Logging

I have a Spring Boot/Spring MVC REST app that has a GET mapping endpoint for ex.
#GetMapping(value = "/person")
public ResponseEntity<Person> getPerson(#RequestParam final String personID)
{
//service call for a person
return new ResponseEntity.ok(personObj);
}
I am using PostMan to hit the endpoint and I have the spring boot jar running and something I noticed was that every PUT and POST method is logged but when it came to GET requests, they were not logged. The only time I got a GET in the running spring boot server logs was if I hit the wrong endpoint path for i.e localhost:8080/personn (misspelling) the log would show the URL with the requestparam value appended to the URL like "GET /personn?personID=123 HTTP/1.1" 404 - "-" "PostmanRuntime
It seems like successful GET calls are not logged but unsuccessful GET calls are logged. Is this normal behavior?
If personID was sensitive data then I should probably use POST?
You can set the logging level of the Spring web package to DEBUG in the application.properties, something like:
logging.level.org.springframework.web=debug
or in recent version of Spring Boot:
logging.level.web=debug

Spring Boot in Cloud Foundry (PCF) disable Whitelabel Error Page

Related question:
Spring Boot Remove Whitelabel Error Page
For my case,
I disabled whitelabel by setting whitelabel.enabled = false, and I also exclude ErrorMvcAutoConfiguration. It worked in regular spring boot service. But I deployed the same service on PCF cloud foundry, then spring still want to redirect error to /error page.
Any help and suggestion is welcome.
Edit:
I added exclude annotation on Application, then it works on PCF.
Previously I added exclude configuration in application.yml, then it didn't work on PCF
You need to create a separate endpoint /error and then handle it in the method. I would suggest you to maintain a separate controller infact. My code would look something like this
#RestController
#RequestMapping(path = "/error")
public class ErrorController {
#ApiOperation(value = "Error Page", notes = "Error Page")
#GetMapping
public String error() {
return "Some Error Occurred and I will Graciously show the Error"
}
}
It turns out circuit breaker service set exclusion property first, than local application.yml didn't take effect. If I add exclusion property in repo, then it take preference.
I feel this is kind of spring bug, since exclusion is list, it should include all items, instead of taking the first configuration only.

How can I see the json coming from the client when using Spring-MVC?

A client software is trying to access my Spring-MVC rest server, but it's getting a 400 (Bad Request) response every time. I know my server is fine (it's in use by many other clients), but I cannot debug the client application, so I cannot see what it is sending.
Is there a way for me to see what JSON I am receiving before Spring tries to convert it to an entity and fails? It's okay if I can only do this at debug time, I just need to be able to give support to this application's creators.
Just in case, here is the spring-mvc controller method:
#Named
#RequestMapping(value = "/taskmanager/task")
public class TaskManagerTaskRest {
#RequestMapping(value = "", method = RequestMethod.POST)
#ResponseBody
public void createTask(#RequestBody Task task, HttpServletRequest request,
HttpServletResponse response) throws CalabacinException {
// This code never gets executed because the Task json is invalid, but I don't know how I could see it.
...
...
}
}
Try to use Fiddler. It will help you to catch HTTP requests/responses. You will be able to see your JSON.
You can create and use a AbstractRequestLoggingFilter filter implementation and conditionally log the relevant parts of the request. You should use ContentCachingRequestWrapper to wrap the request.

How to send the send status code as response for 404 instead of 404.jsp as a html reponse in spring?

I created web application in spring and handled exception mappings for 404 and 500.If system doesn't find any resources for requested URL it redirects into custom 404.jsp instead of regular 404 page.Everything works fine till have decided to add a webservice in my app.I have included one more controller as a webservice there is no view for this controller and this needs to be invoke through curl command.
User may get into change the curl script.If they changed the URL it should show 404 status code.But it returns the custom 404.jsp as a html response instead of status code.Because dispatcher servlet will takes all urls with /*.
How I can solve this issue?
Please share your suggestions.
Spring 3.2 introduced the #ControllerAdvice, and as mentioned in the documentation:
It is typically used to define #ExceptionHandler
That means you can use the #ControllerAdvice to assist your #Controller like the following:
#ControllerAdvice
class GlobalControllerExceptionHandler {
#ResponseStatus(HttpStatus.NOT_FOUND) // 404
#ExceptionHandler(Exception.class)
public void handleNoTFound() {
// Nothing to do
}
}
For further details please refer to this tutorial and this answer.

Resources