Reputation: 65278
I have a spring boot REST application. I need to return a status code of 400 bad request when the path does not exists. Consider:
This is a good url
localhost:8080/mypath?name=test
Bad Path (return status 400)
localhost:8080/mybadpath?name=test
How can I do this using spring boot
Upvotes: 1
Views: 2709
Reputation: 1
Just code like this in your controller, the HttpServletResponse
will be autowired :
@RequestMapping("/page")
public String page(HttpServletResponse response) throws IOException {
if(doSomeThing()){
return "success";
} else {
response.sendError(HttpStatus.BAD_REQUEST.value(),"Message:400");
return "";
}
}
Upvotes: 0
Reputation: 75964
I would try to extend the ResponseEntityExceptionHandler
class and override the handleNoHandlerFoundException
to adjust it to return as bad request.
Something like
@ControllerAdvice
public class AppRestExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleNoHandlerFoundException(final NoHandlerFoundException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) {
HttpStatus newStatus = HttpStatus.NOT_FOUND;
return handleExceptionInternal(ex, null, headers, newStatus, request);
}
}
Upvotes: 0
Reputation: 40078
This works for spring boot-2.1.3 by implementing ErrorController
@Controller
public class CustomErrorController implements ErrorController {
private static final String PATH = "/error";
@RequestMapping(value = PATH)
public ResponseEntity<String> error(WebRequest webRequest, HttpServletResponse response) {
return ResponseEntity.badRequest().body("");
}
@Override
public String getErrorPath() {
return PATH;
}
}
Main
@SpringBootApplication
public class BotMain {
public static void main(String[] args) {
SpringApplication.run(BotMain.class, args);
}
}
Upvotes: 4
Reputation: 936
I don't know why you would want to do this. This is a very bad practice. I would recommend changing the design. If you want to do this, there are a couple of things you can do to achieve this-
Upvotes: 0
Reputation: 23119
I must be missing something, especially with the bounty on this. Isn't this really easy? I've done something like this in the past:
@Controller
class foo {
@GetMapping("**")
public static ResponseEntity blah() {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
}
}
Since Spring prioritizes the longest mapping that matches a particular path, this only wins if nothing else matches.
Go ahead...point out what I'm missing please.
Upvotes: 0