Skip to content
Open
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 @@ -27,6 +27,7 @@
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

@RestControllerAdvice
public class GlobalExceptionHandler {
Expand Down Expand Up @@ -64,6 +65,13 @@ public Result<?> handleHttpMessageNotReadableException(HttpMessageNotReadableExc
return Result.error(HttpStatus.BAD_REQUEST.value(), "Invalid request body");
}

@ExceptionHandler(MethodArgumentTypeMismatchException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Result<?> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex) {
log.warn("Invalid request parameter: {}", ex.getName());
return Result.error(HttpStatus.BAD_REQUEST.value(), "Invalid request parameter: " + ex.getName());
}

@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,32 @@ void preservesBadRequestBusinessStatusAndEnvelope() throws Exception {
.andExpect(jsonPath("$.message").value("failure-400"));
}

@Test
void returnsBadRequestWhenRequestParamTypeIsInvalid() throws Exception {
mockMvc.perform(get("/test/number").param("startTime", "invalid"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.code").value(400))
.andExpect(jsonPath("$.message").value("Invalid request parameter: startTime"));
}

@Test
void acceptsValidRequestParamType() throws Exception {
mockMvc.perform(get("/test/number").param("startTime", "1000"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.data").value(1000));
}

@RestController
static class FailingController {

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

@GetMapping("/test/number")
Result<Long> number(@RequestParam Long startTime) {
return Result.ok(startTime);
}
}
}
Loading