如何为我的404页面使用自定义json?
实际上,我需要的是能够为我的应用程序创建自定义json错误。
例如404,401,403,422 ...
我搜索了很多,发现的是:
package ir.darsineh.lms.http.exceptionHandler;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(NoHandlerFoundException.class)
public void springHandleNotFound(HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.NOT_FOUND.value());
}
}
这是我得到的错误:
Ambiguous @ExceptionHandler method mapped for [class org.springframework.web.servlet.NoHandlerFoundException]
我需要我的api响应正文json是这样的:
{"code": 404, "message": "page not found"}
最佳答案
首先,如果未找到处理程序,则应让Spring MVC引发异常:spring.mvc.throw-exception-if-no-handler-found=true
然后,必须使用@ControllerAdvice
捕获异常:
@ControllerAdvice
public class CustomAdvice {
// 404
@ExceptionHandler({ NoHandlerFoundException.class })
@ResponseBody
@ResponseStatus(HttpStatus.NOT_FOUND)
public CustomResponse notFound(final NoHandlerFoundException ex) {
return new CustomResponse(HttpStatus.NOT_FOUND.value(), "page not found");
}
}
@Data
@AllArgsConstructor
class CustomResponse {
int code;
String message;
}
不要忘记将@EnableWebMvc批注添加到您的应用程序。
关于spring - 未找到Spring Boot 2.2.5 404页面自定义json响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60960881/