Maybe not that relevant, but I came across to a similar need: change the 5xx error to 4xx error for authentication header missing.
The controller is as follows:
@RequestMapping("list") public ResponseEntity<Object> queryXXX(@RequestHeader(value = "Authorization") String token) { ... }
When you cURL it without the authorization header you get a 5xx error:
curl --head -X GET "http://localhost:8081/list?xxx=yyy" -H "accept: */*" HTTP/1.1 500 ...
To change it to 401 you can
@ExceptionHandler(org.springframework.web.bind.MissingRequestHeaderException.class) @ResponseBody public ResponseEntity<Object> authMissing(org.springframework.web.bind.MissingRequestHeaderException ex) { log.error(ex.getMessage(), ex); return IResponse.builder().code(401).message(ex.getMessage()).data(null).build(); } @Data public class IResponse<T> implements Serializable { private Integer code; private String message = ""; private T data; ... }
You can verify it by an automation test:
@Test void testQueryEventListWithoutAuthentication() throws Exception { val request = get("/list?enrollEndTime=1619176774&enrollStartTime=1619176774&eventEndTime=1619176774&eventStartTime=1619176774"); mockMvc.perform(request).andExpect(status().is4xxClientError()); }