简体   繁体   中英

Spring boot - How to customize http request error 400 instead of https

I'm creating a Restful API and I want JSON responses. I enabled Https by default and when I try to access endpoints with http protocol I get a 400 error with this response message:

Bad Request This combination of host and port requires TLS.

I want to return a JSON object instead, something like:

{
   "message": "Bad Request HTTPS required",
   "status": 400,
   "timestamp": "2022-04-13T12:05:25.332"
}

How can I implement this in Spring Boot??

You can create custom Exception handler with the @ControllerAdvice annotation and cach any Exception, with the @ExceptionHandler annotation, and then return with a custom json response.

@ControllerAdvice
public class ApiExceptionHandler {

   //The exception can be different or eather a list of exceptions like value = { ExceptionType1.class, ExceptionType2.class}  
   @ExceptionHandler(value = Exception.class)
   public ResponseEntity<Object> handleBadRequestException(BadRequestException e) {

     HttpStatus httpStatus = HttpStatus.OK;

     CustomResponseClass response = new CustomResponseClass(CustomEnum.RESPONSE_CODE, e.getMessage(), httpStatus.value(), ZonedDateTime.now(ZoneId.of("Z")));
     
     return new ResponseEntity<>(response, httpStatus);
   }


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM