I am using spring for my project and a question arises in my mind that what is the basic difference between these two HttpStatus
return ResponseEntity.status(HttpStatus.SC_NOT_FOUND).body("Email address not found");
return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Token Expired");
The first one is from the apache servlet API for status codes from Interface HttpServletResponse found here
SC_NOT_FOUND - Status code (404) indicating that the requested
resource is not available.
The second one is from spring framework http status codes constants from here
NOT_FOUND 404 Not Found.
For spring Framework (& spring boot) the second one is used widely.
There is no difference, it is same status code for HTTP from different libraries.
Related
I am currently working on a Spring Web services(SOAP) project. The requirement is to validate the request payload and return the error response if validation fails and log it. I have extended PayloadValidatingInterceptor to return custom validation message.
As part of logging requirement, we need to print the header values from Request Headers (HttpServletRequest) for tracking purpose.
How to access HttpServletRequest in the implementation of PayloadValidatingInterceptor?
Is it possible to inject HttpServletRequest?
version details:
Spring-Boot : 2.2.6
Spring-ws-core : 3.0.8
Please help.
I need to log 401 unauthorized errors in my Springboot application.
I wanted to log this for a certain end point in my app since its unauthorized error I know this attempt will be caught when invoking the api at the beginning itself.
Are there anyways I can keep track of this in spring boot?
I tried through WebSecurityConfig but didnt help.
I am using springboot 2.
Thanks in advance.
There are 2 ways I can think of, but probably there are more
use custom #ExceptionHandler method in your controller and make it sensitive to UnauthorizedException.class
Use Filter to introspect into request/response - and log whatever you want in case of response beeing 401.
You can get hold of the authentication entry point and handle some 401 logic in the http
security config:
.authenticationEntryPoint((httpServletRequest, httpServletResponse, e) -> {
log.warn(e.getMessage());
httpServletResponse.setStatus(401);
httpServletResponse.getWriter().print(e.getMessage());
})
I am having a hard time in Chaos Monkey For Spring Boot regarding error responses when a user POSTs an invalid (like {"level": -2}update via REST to our actuator endpoint where one can update options of the behavior of CMSB (only positive levels are allowed). In the first image, I set the management.server.port to 8888 and the app port to 8080. When posting a new property to the CMSB REST API I am getting the following response (which is not what we would have expected):
And in case I leave the management port at the same port the same as the app I am getting the following response:
For both cases we would have expected the same error response (the second one). So we're asking us (at CMSB) whether this is an intended behavior of spring boot and if not, what our options are to get around writing our own error response handler in case the management port is different from the app port.
Please note that this is not about the intended behavior of chaos monkey for spring boot but rather about whether this is a spring boot bug or not. In both cases we would like to have a detailed error response so a user knows what's wrong. Under the hood we are using the #Validated annotation in combination with something like this to validate inputs:
#Data
#NoArgsConstructor
#Validated
#JsonInclude(JsonInclude.Include.NON_NULL)
public class AssaultPropertiesUpdate {
#Nullable
#Min(value = 1)
#Max(value = 10000)
private Integer level;
On a side note: in both cases the error message in the logs is correct. But only in the second case is this error message
WARN 4477 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public org.springframework.http.ResponseEntity<?> de.codecentric.spring.boot.chaos.monkey.endpoints.ChaosMonkeyRestEndpoint.updateAssaultProperties(de.codecentric.spring.boot.chaos.monkey.endpoints.AssaultPropertiesUpdate): [Field error in object 'assaultPropertiesUpdate' on field 'level': rejected value [-2]; codes [Min.assaultPropertiesUpdate.level,Min.level,Min.java.lang.Integer,Min]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [assaultPropertiesUpdate.level,level]; arguments []; default message [level],1]; default message [must be greater than or equal to 1]] ]
used as the response payload.
Minimal example project: https://github.com/fletchgqc/mediator
Start the project with mvn spring-boot:run. and then do a POST against http://localhost:8080/actuator/chaosmonkey/assaults with the the payload: {"level": -2}. Correct error response should be shown (like in image 2).
Then stop the project, to https://github.com/fletchgqc/mediator/blob/master/src/main/resources/application.properties add management.server.port=8888 and start the app again. Do a POST against http://localhost:8888/actuator/chaosmonkey/assaults with the same payload as before. The wrong error message should appear (like in image 1).
Looks like the spring team fixed it here: https://github.com/spring-projects/spring-boot/issues/21036
How do we handle incoming request to a wrong contextpath in spring mvc?
I have deployed a spring mvc application having contextpath as
http://exampledomain.com/mycontext
But when I try accessing url http://exampledomain.com/wrongcontext I get error as HTTP Status 404 - /wrongcontext/
I have implemented error handling which works fine for all wrong url when correct context path is used but it does not work for wrong context path.
I am trying to understand how do we redirect all incoming request to specific page in production environment..
thanks in advance
Your application can only see requests to its context /mycontext There is nothing your application can do about requests to other contexts.
You can however deploy an application at the root context / and implement an error handler there.
Check out this answer: How to customize JBoss AS7 404 page
That answer relates to JBoss, but the same idea will apply on other servers.
It is not possible to handle wrong context path requests in Spring since it only will handle the requests which goes to your context root. You have to take a look at server configuration parameters to redirect those kind of requests. If you are working on Tomcat, check path parameter of context.xml:
https://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Defining_a_context
We can use #ExceptionHandler inside a #Controller or #ControllerAdvice to handle such kind of exceptions and decide on the view page to be rendered.
#ExceptionHandler({ HttpRequestMethodNotSupportedException.class,
HttpMediaTypeNotSupportedException.class, HttpMediaTypeNotAcceptableException.class,
MissingPathVariableException.class, MissingServletRequestParameterException.class,
ServletRequestBindingException.class,MethodArgumentNotValidException.class, MissingServletRequestPartException.class,
NoHandlerFoundException.class})
public ModelAndView handleException(){
return new ModelAndView("errorpage");
}
I found a very strange phenomenon when use spring boot, at first I used jetty, there is a PUT request, it's request body is a JSON, if client input an unnecessary property, e.g. "foo":"bar", Spring mvc does not have any error messge, in swagger ui there is only :
but if I changed to tomcat,Spring mvc will return a clear exception, like this:
{
"status": 400,
"error": "Bad Request",
"message": "Could not read document: Unrecognized field \"foo\" (class com.), not marked as ignorable (......)\n at [Source: java.io.PushbackInputStream#51c5845a; line: 2, column: 12] (through reference chain: \"foo\"]);
"exception": "org.springframework.http.converter.HttpMessageNotReadableException"
}
why spring mvc can't supply error message when use jetty?
Error 400 Bad Request is unique, as it means the request itself is bad. So bad, that not even the container knows what is it, or can even recognize it as a HTTP Request.
If the container can't recognize it as an HTTP Request, then how will it know what context (webapp) to send the request (that doesn't exist) to in order for the Error Handling logic to process it?
Spring MVC sometimes behaves very strange, I had a spring MVC error 400 when posting a form, the problem that made MVC return 400 bad request was actually the lack of BindingResult. Please see this question here.
There are many reasons why spring can return 400 Bad request.