我正在开发 Spring Boot JPA 示例,在此示例中,我使用ResponseEntityExceptionHandler
开发了自定义@ControllerAdvice
类。
{
"createUser": "string",
"lastUpdateUser": "string",
"employeeName": "John Doe",
"employeeEmail": "john.doe@gmail.com" //line-4
"status": "string"
}
如果您查看POST
请求,那么在第4行,我错过了输入分号(,)的可能性,因此该请求被视为无效。现在我遇到400 HTTP
错误,但是我想通过在ExceptionalHandler
类中处理自定义错误消息来显示它。有什么帮助吗?
答案 0 :(得分:1)
您可以简单地实现以下方法。这将为result
自定义响应。
/* remove default value */
ALTER TABLE `result` ALTER `mid` DROP DEFAULT;
/* change engine, add id column, add composite primary key */
ALTER TABLE `result`
ENGINE=MyISAM,
CHANGE COLUMN `mid` `mid` INT(11) NOT NULL FIRST,
ADD COLUMN `id` INT(11) NOT NULL AUTO_INCREMENT AFTER `mid`,
ADD PRIMARY KEY (`mid`, `id`);
答案 1 :(得分:0)
创建您自己的自定义例外。
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
public BadRequestException(String message) {
super(message);
}
}
在@ControllerAdvice类中处理您的自定义异常
@ExceptionHandler(BadRequestException.class)
public ResponseEntity<ErrorResponse> handleException(
BadRequestException e) {
// improve error logging when used.
log.error("Unexpected Bad Request. ", e);
return new ResponseEntity<>(new ErrorResponse("Unexpected Bad Request. " + e.getMessage()),
HttpStatus.BAD_REQUEST);
}