我正在尝试阅读Linux源代码(2.6.11)
在异常处理程序中,在entry.s,error_code:
movl $(__USER_DS), %ecx
movl %ecx, %ds
movl %ecx, %es
Run Code Online (Sandbox Code Playgroud)
我不知道为什么在这里加载用户数据段.由于它应该进入在内核模式下运行的异常处理程序代码,因此选择器应该是__KERNEL_DS.
我检查了其他版本的代码,他们在这个地方也做了同样的事情.
我想知道是否有可能在发生内部服务器错误时设置一些自定义标头值?我目前在做:
public class FooExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
// context.Result already contains my custom header values
context.Result = new InternalServerErrorResult(context.Request);
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我还想设置一些标头值,但是虽然它出现在请求中,但响应不包含它.
有办法做到这一点吗?
我想根据响应对象错误动态返回 HTTPStatus 代码,如 400、400、404 等。我被提到了这个问题 -使用 spring 3 restful以编程方式更改 http 响应状态,但它没有帮助。
我有一个带有@ExceptionHandler方法的控制器类
@ExceptionHandler(CustomException.class)
@ResponseBody
public ResponseEntity<?> handleException(CustomException e) {
return new ResponseEntity<MyErrorResponse>(
new MyErrorResponse(e.getCode(), ExceptionUtility.getMessage(e.getMessage())),
ExceptionUtility.getHttpCode(e.getCode()));
}
Run Code Online (Sandbox Code Playgroud)
ExceptionUtility是一个类,我在其中使用了上面使用的两种方法(getMessage和getCode)。
public class ExceptionUtility {
public static String getMessage(String message) {
return message;
}
public static HttpStatus getHttpCode(String code) {
return HttpStatus.NOT_FOUND; //how to return status code dynamically here ?
}
}
Run Code Online (Sandbox Code Playgroud)
我不想检查 if 条件并相应地返回响应代码,有没有其他更好的方法来做到这一点?
我们需要在所有端点支持html和json响应.
html将由我们自己的前端应用程序使用,json将由第三方API集成使用.
我们使用ContentNegotiatingViewResolver分别对html和json内容使用JstlView和MappingJackson2JsonView,效果很好.使用单个控制器方法,我们获得基于url扩展名的html/json输出.
我们希望通过@ControllerAdvice/@ExceptionHandler为全局ExceptionHandler提供类似的技术.但在解析为视图之前,似乎没有考虑内容类型.
如何让ExceptionHandler根据url.extension选择正确的视图来生成html或json?(注意:我不想使用@ResponseBody或ResponseEntity,因为我需要一个ModelAndView来输出基于html的错误页面)
我可以创建一个自定义视图解析器来为ExceptionHandling执行此操作吗?如何在Spring配置中将其拼接在一起,我的ContentNegotiationViewResolver用于正常响应?
为了在整个应用程序中实现统一的异常处理,我将REST错误处理与Spring solution#3 @ControllerAdvice一起使用,并与一起使用@ExceptionHandler。
春季版本:4.3.22.RELEASE
Spring Boot版本:1.5.19.RELEASE
这是一个Spring Boot应用程序,下面是我的程序包结构。
src/main/java
com.test.app.controller
MyRestController.java -- This is my Rest controller
com.test.app.handler
RestExceptionHandler.java -- This is my ControllerAdvice class
Run Code Online (Sandbox Code Playgroud)
以下是我的ControllerAdvice代码,其中一个Controller引发,InvalidDataException但仍未@ExceptionHandler调用相应的控制器。相反,我Unexpected 'e'使用http 400作为响应正文。
@ControllerAdvice
public class RestExceptionHandler {
@ExceptionHandler(InvalidDataException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public @ResponseBody ErrorResponse handleValidationError(final InvalidDataException ex,
final WebRequest request) {
log.error("InvalidDataException message:{} ", ex.getMessage());
return getExceptionResponse("Failed with Invalid data" + ex.getMessage(), HttpStatus.BAD_REQUEST.value());
}
private ErrorResponse getExceptionResponse(final String message, final Integer errorCode) …Run Code Online (Sandbox Code Playgroud) exceptionhandler spring-boot spring-restcontroller controller-advice
在我的 Spring Boot 应用程序中,我有一个用于生成和使用 JSON 请求的 post 请求的控制器,并且我已使用 HttpMediaTypeNotAcceptableException 为该控制器定义了 @ExceptionHandler 来捕获 HttpMediaTypeNotAcceptableException(406 状态代码)异常。
现在,每当我使用错误的 ACCEPT 标头(例如 application/pdf)调用 post 请求时,定义的异常都不会被调用。
我不想定义 ControllerAdvice,因为我想为此控制器抛出特定错误。
代码:
@RestController
@RequestMapping("/school")
public class SchoolCotroller {
@Autowired
private SchoolService schoolService;
@PostMapping(produces = "Application/Json", consumes = "Application/Json")
@ResponseStatus(HttpStatus.CREATED)
public School postData(@Valid @RequestBody School school) {
return schoolService.save(school);
}
@ExceptionHandler(HttpMediaTypeNotAcceptableException.class)
String handleMediaTypeNotAcceptable(
final HttpMediaTypeNotAcceptableException exception,
final NativeWebRequest request) {
return "acceptable MIME type:" + MediaType.APPLICATION_JSON_VALUE;
}
}
Run Code Online (Sandbox Code Playgroud)
卷曲:
curl --location --request POST 'http://localhost:8080/school' \
--header 'Accept: application/pdf' \
--header …Run Code Online (Sandbox Code Playgroud) 我将此处给出的异常处理(https://github.com/tiangolo/fastapi/discussions/6678)添加到我的代码中,但我想打印完整的请求正文以查看完整的内容。但是,当我等待时,request.json()它永远不会终止。request.json()返回一个协程,因此我需要等待协程完成才能打印结果。如果向端点发送了无效请求,如何打印请求内容?
来自 github 的代码示例,我在错误处理程序和一个简单的端点中进行了 2 处更改。
import logging
from fastapi import FastAPI, Request, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel
app = FastAPI()
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(
request: Request, exc: RequestValidationError
) -> JSONResponse:
exc_str = f"{exc}".replace("\n", " ").replace(" ", " ")
logging.error(f"{request}: {exc_str}")
body = await request.json() # This line was added by me and never completes
logging.error(body) # This line was added by me
content = …Run Code Online (Sandbox Code Playgroud) 我想将@Valid 注释与@RequestBody 注释一起使用,并在我自己的用@ExceptionHandler 注释注释的方法中处理错误。我想总是返回 ReponseEntity 的实例。但是当我为 MethodArgumentNotValidException 创建 ExceptionHandler 时,我无法启动我的应用程序。我的控制器看起来像这样:
@PostMapping("/places/report")
public ResponseEntity<WrongPlaceReportDTO> report(@RequestHeader(value="Accept-Language") String acceptLanguage,
WrongPlaceReportDTO result = wrongPlaceReportService.save(wrongPlaceReportDto, Locale.forLanguageTag(acceptLanguage));
return new ResponseEntity<WrongPlaceReportDTO>(result, HttpStatus.OK);
}
Run Code Online (Sandbox Code Playgroud)
我的全局异常处理程序如下所示:
@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ResponseEntity<RestResponse<Void>> handleMethodArgumentNotValidException(MethodArgumentNotValidException error, WebRequest request) {
return parseErrors(error.getBindingResult());
}
private ResponseEntity<RestResponse<Void>> parseErrors(BindingResult bindingResult){
return new ResponseEntity<RestResponse<Void>>(HttpStatus.BAD_REQUEST);
}
}
Run Code Online (Sandbox Code Playgroud)
当我开始我的 SpringBoot 应用程序时,我得到了这个:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'handlerExceptionResolver' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception …Run Code Online (Sandbox Code Playgroud) 我有一个带有控制器和服务的 springboot 项目。和 GlobalExceptionHandler 像 -
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(DataIntegrityViolationException.class)
public ResponseEntity<Object> handle(DataIntegrityViolationException e, WebRequest request) {
....
String requestPath = ((ServletWebRequest)request).getRequest().getRequestURI();
// I am using this requestPath in my output from springboot
...
}
}
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我如何在我的单元测试类中编写模拟吗
((ServletWebRequest)request).getRequest().getRequestURI()
我已经为我的一个spring控制器编写了自定义异常处理程序类,以验证来自请求参数的email属性是否采用正确的格式。因此,创建了一个扩展ResponseEntityExceptionHandler类的新类,并使用编写了一个方法@ExceptionHandler。
但是在春季启动应用程序启动期间,我遇到了以下异常,该异常正在停止运行我的项目。有人可以帮我解决这个问题吗?
服务器启动期间发生异常:
org.springframework.beans.factory.BeanCreationException:在类路径资源[org / springframework / boot / autoconfigure / web / servlet / WebMvcAutoConfiguration $ EnableWebMvcConfiguration.class]中创建名称为'handlerExceptionResolver'的bean时出错。
嵌套的异常是org.springframework.beans.BeanInstantiationException:无法实例化[org.springframework.web.servlet.HandlerExceptionResolver]:工厂方法'handlerExceptionResolver'抛出了异常;
嵌套异常是java.lang.IllegalStateException:为[类org.springframework.web.bind.MethodArgumentNotValidException]映射的模糊@ExceptionHandler方法:{public com.TestVO com.handler.exception.TestExceptionHandler.methodArgumentNotValidException(org.springframework.web.bind .MethodArgumentNotValidException),公共最终org.springframework.http.ResponseEntity org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest)抛出java.lang.Exception}
自定义类要处理MethodArgumentNotValidException:
@ControllerAdvice
public class ExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorVO processValidationError(MethodArgumentNotValidException ex) {
BindingResult result = ex.getBindingResult();
List<FieldError> fieldErrors = result.getFieldErrors();
FieldError fieldError = fieldErrors.get(0);
ErrorVO dto = new ErrorVO(fieldError.getDefaultMessage());
return dto;
}
}
Run Code Online (Sandbox Code Playgroud) 我正在研究全局异常中间件的实现,我想用单元测试来覆盖中间件。下面你看看我走了多远。
这是单元测试的代码。
[Fact]
public async Task MethodName_StateUnderTest_ExpectedBehavior()
{
//Arrange
IExceptionHandlerFeature exceptionHandlerFeature = new ExceptionHandlerFeature {Error = new NotFoundException()};
IFeatureCollection features = new FeatureCollection();
features.Set(exceptionHandlerFeature);
var context = new DefaultHttpContext(features);
context.Response.Body = new MemoryStream();
//Act
await ExceptionMiddleware.HandleException(context);
//Assert
context.Response.StatusCode.Should().Be((int) HttpStatusCode.NotFound);
}
Run Code Online (Sandbox Code Playgroud)
这是 ExceptionMiddleware.Handle 方法的代码
public static async Task HandleException(HttpContext context)
{
var contextFeature = context.Features.Get<IExceptionHandlerFeature>();
if (contextFeature == null)
{
return;
}
if (contextFeature.Error is AppValidationException validationException)
{
context.Response.StatusCode = (int) HttpStatusCode.BadRequest;
var failures = JsonConvert.SerializeObject(validationException.Failures);
await context.Response.WriteAsync(
new ErrorDetails
{ …Run Code Online (Sandbox Code Playgroud) unit-testing middleware httpcontext exceptionhandler .net-core
我有一个如下所示的 pojo(请假设一个控制器和其余代码。应用程序位于 Spring boot 中):
@Getter @Setter
@AllArgsConstructor @NoArgsConstructor
public class User {
@NotBlank(message = "userName is blank")
private String userName;
@NotBlank(message = "secretKey is blank")
private String secretKey;
}
Run Code Online (Sandbox Code Playgroud)
并定义了一个 ExceptionHandler 类,@ControllerAdvice并定义了一个方法,如下所示:
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = {MethodArgumentNotValidException.class})
protected ResponseEntity<ErrorResponse> handleMethodArgNotValidException(MethodArgumentNotValidException ex,Locale locale) {
// code to handle exception.
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = {WebExchangeBindException.class})
protected ResponseEntity<ErrorResponse> handleException(WebExchangeBindException ex, Locale locale) {
// code to handle exception.
}
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,即使两个字段都有验证错误,客户端也只能得到一个。
我想问有什么方法可以列出该端点响应中的所有验证错误吗?
curl --location --request POST 'localhost/api/login' \
--header 'Content-Type: application/json' \ …Run Code Online (Sandbox Code Playgroud) 我试图通过ExceptionHandler处理未捕获的异常.遵循JSF2完整参考中的代码,我已经为我的处理程序创建了类.但是当我部署我的应用程序时,它会抛出下一个stackTrace:
SEVERE: Critical error during deployment:
com.sun.faces.config.ConfigurationException: Factory 'javax.faces.context.ExceptionHandlerFactory' was not configured properly.
at com.sun.faces.config.processor.FactoryConfigProcessor.verifyFactoriesExist(FactoryConfigProcessor.java:305)
at com.sun.faces.config.processor.FactoryConfigProcessor.process(FactoryConfigProcessor.java:219)
at com.sun.faces.config.ConfigManager.initialize(ConfigManager.java:360)
at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:225)
at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:4750)
at com.sun.enterprise.web.WebModule.contextListenerStart(WebModule.java:550)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:5366)
at com.sun.enterprise.web.WebModule.start(WebModule.java:498)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:917)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:901)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:733)
at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:2019)
at com.sun.enterprise.web.WebContainer.loadWebModule(WebContainer.java:1669)
at com.sun.enterprise.web.WebApplication.start(WebApplication.java:109)
at org.glassfish.internal.data.EngineRef.start(EngineRef.java:130)
at org.glassfish.internal.data.ModuleInfo.start(ModuleInfo.java:269)
at org.glassfish.internal.data.ApplicationInfo.start(ApplicationInfo.java:301)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:461)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:389)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:348)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:363)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1085)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:95)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1291)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1259)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:461)
at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:212)
at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
at com.sun.enterprise.v3.services.impl.ContainerMapper$Hk2DispatcherCallable.call(ContainerMapper.java:354)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at …Run Code Online (Sandbox Code Playgroud) exceptionhandler ×13
java ×6
spring-boot ×6
spring ×4
validation ×2
.net-core ×1
c# ×1
content-type ×1
data-segment ×1
fastapi ×1
freeze ×1
glassfish ×1
glassfish-3 ×1
http-headers ×1
httpcontext ×1
jsf ×1
linux ×1
middleware ×1
python ×1
starlette ×1
unit-testing ×1