Spring MVC使用@ExceptionHandler注解异常处理
控制层异常处理接口exceptionBaseHandler控制层exceptionController
创建 exceptionBaseHandler类,并在该类中使用 @ExceptionHandler 注解声明异常处理方法
控制层异常处理接口exceptionBaseHandler
package control
;
import org
.springframework
.web
.bind
.annotation
.ExceptionHandler
;
import javax
.servlet
.http
.HttpServletRequest
;
import java
.sql
.SQLException
;
public class exceptionBaseHandler {
@ExceptionHandler
public String
exception(HttpServletRequest httpServletRequest
,Exception ex
){
httpServletRequest
.setAttribute("ex", ex
);
if (ex instanceof SQLException
) {
return "sql-error";
}else {
return "error";
}
}
}
控制层exceptionController
package control
;
import org
.springframework
.stereotype
.Controller
;
import org
.springframework
.web
.bind
.annotation
.RequestMapping
;
import java
.sql
.SQLException
;
@Controller
@
RequestMapping("/exception")
public class exceptionController extends exceptionBaseHandler
{
@
RequestMapping("/login")
public String
login() throws Exception
{
throw new SQLException("data base error");
}
}