Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
Expand Down Expand Up @@ -64,6 +65,13 @@ public Result<?> handleHttpMessageNotReadableException(HttpMessageNotReadableExc
return Result.error(HttpStatus.BAD_REQUEST.value(), "Invalid request body");
}

@ExceptionHandler(MissingServletRequestParameterException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Result<?> handleMissingServletRequestParameterException(MissingServletRequestParameterException ex) {
String message = ex.getParameterName() + " is required";
return Result.error(HttpStatus.BAD_REQUEST.value(), message);
}

@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Result<?> handleException(Exception ex) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
Expand Down Expand Up @@ -56,12 +57,25 @@ void preservesBadRequestBusinessStatusAndEnvelope() throws Exception {
.andExpect(jsonPath("$.message").value("failure-400"));
}

@Test
void returnsBadRequestWhenRequiredRequestParamIsMissing() throws Exception {
mockMvc.perform(get("/test/required-param"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.code").value(400))
.andExpect(jsonPath("$.message").value("key is required"));
}

@RestController
static class FailingController {

@GetMapping("/test/business/{code}")
Result<Void> fail(@PathVariable int code) {
throw new BusinessException(code, "failure-" + code);
}

@GetMapping("/test/required-param")
Result<String> requiredParam(@RequestParam String key) {
return Result.ok(key);
}
}
}
Loading