Spring Bood @ControllerAdvice

Usage

Case: Hello

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@ControllerAdvice
class SystemErrorController {
private val logger = LogManager.getLogger(SystemErrorController::class)

@ExceptionHandler(Exception::class)
fun handleError(ex: Exception): ResponseEntity<Any> {
logger.error("handleError(): $ex")
val error = Error(500, HttpStatus.INTERNAL_SERVER_ERROR.name)
return ResponseEntity(error, HttpStatus.INTERNAL_SERVER_ERROR)
}


@ExceptionHandler(MethodArgumentNotValidException::class, MissingServletRequestParameterException::class)
fun handleArgumentError(ex: Exception): ResponseEntity<Any> {
logger.error("handleArgumentError(): $ex")
val error = Error(ErrorCode.BODY_ARGUMENT_IS_INVALID.value, ex.message ?: "")
return ResponseEntity(error, HttpStatus.BAD_REQUEST)
}
}


// Unit Testing
StandaloneMockMvcBuilder mockMvc = MockMvcBuilders.standaloneSetup(new OrderController()).setControllerAdvice(adviceController);
RestAssuredMockMvc.standaloneSetup(mockMvc);